Sorry for my bad English. I code a program that have to list entered names. But if entered name is already in the array, user have to reenter a different name. I left a picture that shows what is happening when I run the code
import java.util.Scanner;
public class list {
public static void main(String[] args) {
int numberofhumans;
Scanner al = new Scanner(System.in);
System.out.print("Enter the number of person: ");
numberofhumans = al.nextInt();
String[] list = new String[numberofhumans];
for (int i = 0; i < numberofhumans; i ) {
System.out.print("Enter the name:");
list[i] = al.nextLine();
for (int j = 0; j < i; j ) {
if (list[i] == list[j]) {
System.out.println("Name you just typed is already in your list. Enter a different name.");
i--;
}
}
}
for (String string : list) {
System.out.println(string);
}
al.close();
}
}
https://i.stack.imgur.com/lbC2X.png
CodePudding user response:
Your issue is this line:
if (list[i] == list[j])
This checks if the 2 objects are equal, which they are not even if their content is the same. You need to use .equals method of String object to compare 2 strings. That should fix the problem:
if (list[i].equals(list[j]))
I would rather use a Set of String instead of an array for a better performance since you won't have to iterate over and over again for each new input. Something like:
Set<String> set = new HashSet<>();
for (int i = 0; i < numberofhumans; i ) {
System.out.print("Enter the name: ");
String name = al.nextLine();
while (set.contains(name)) {
System.out.println("Name you just typed is already in your list. Enter a different name.");
System.out.print("Enter the name: ");
name = al.nextLine();
}
set.add(name);
}
CodePudding user response:
Looking into your code, i found that you are using al.nextLine()
which can return an empty String if the previous element the Scanner gave you was not a whole line. This is why you get prompted twice to enter a name when you run your program. See this post for further details.
Solution: use al.next()
instead.
You are also comparing two String with the ==
operator which is comparing their adresses in memory. This comparison will always return false
Here is as working program:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
int numberofhumans;
Scanner al = new Scanner(System.in);
System.out.print("Enter the number of person: ");
numberofhumans = al.nextInt();
String[] list = new String[numberofhumans];
for (int i = 0; i < numberofhumans; i ) {
System.out.print("Enter the name:");
list[i] = al.next();
for (int j = 0; j < i ; j ) {
if (list[i].equals(list[j])) {
System.out.println("Name you just typed is already in your list. Enter a different name.");
i--;
}
}
}
for (String string : list) {
System.out.println(string);
}
al.close();
}