+ 1
How can i make it work
https://code.sololearn.com/csjLXx7xb0ZX/?ref=app Hey guys, i would like to create a Kind of telephone book. the user has to type the names and After that the numbers and if the user inputs a Name it should return his number. i tried this code on my laptop but it didnt work! any ideas how to improve?
9 odpowiedzi
+ 6
As you wish)
Catch with "for" and 10 records
import java.util.Scanner;
import java.util.ArrayList;
public class Phonebook {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> number = new ArrayList<String>();
for (int x = 1; x <= 10; x++) {
System.out.println("Please insert the " + x + "name and confirm with enter");
name.add(input.next());
}
for (int x = 1; x <= 10; x++) {
System.out.println("Please insert " + name.get(x - 1) + "'s number 'and confirm with enter");
number.add(input.next());
}
for (int x = 0; x < 10; x++) {
System.out.println("type the name of the person whose number you want to receive and confirm with enter");
String y = input.next();
System.out.println(number.get(name.indexOf(y)));
}
}
}
+ 6
I little fixed the code.
It is better to use for input the loop "do while" with the check if you actually don't know how many records in the phonebook.
This code doesn't work on playground, try it in IDE.
import java.util.Scanner;
import java.util.ArrayList;
public class Phonebook {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> number = new ArrayList<String>();
int c = 1;
String str;
do {
System.out.println("Please type the " + c + " name and confirm with enter or type \"exit\" to complete");
str = input.next();
if (!str.equals("exit")) {
name.add(str);
c++;
}
}
while (!str.equals("exit"));
for (int x=0; x < c-1; x++) {
System.out.println("Please type " + name.get(x) + "'s number 'and confirm with enter");
number.add(input.next());
}
do {
System.out.println("type the name of the person whose number you want to receive and confirm with enter or type \"exit\" to complete");
str = input.next();
if (!str.equals("exit")) {
System.out.println(number.get(name.indexOf(str)));
}
}
while (!str.equals("exit"));
}
}
+ 5
To begin, correct the syntax errors: ")", "}".
Read the messages from the compiler.
+ 5
@Jan ok,
I'll try it on laptop a little bit later.
+ 5
@Jan You are welcome
+ 1
alexey i quickly tiped the code in this app, i didnt look for synthax neither is this my Problem. i does Not Work when it comes to comparing y to the name stored in the name Array list
+ 1
thanks
+ 1
thank you! the for loop was plenty cause our task was a list with 10 entrys😁
+ 1
you, sir, made my day!