I'am trying to write a program in Java that collects users favorite names within an array and then prints these names at the end.
NOTE: the length of the array should be defined by the number of names a user enters.
Please take a look at the code and tell me how to fix it. Here is what I have done so far
Scanner input = new Scanner(System.in);
System.out.println("What are your most favorite names?");
String[] favNames = new String[i];
int i = 1;
while (true){
System.out.print("Please enter favorite name number" + i + ": ");
favNames[i-1] = input.next();
System.out.print("Is that all?");
String ans = input.next().toLowerCase();
if(ans.startsWith("y")){
System.out.print("Here is the completed list of your favorite names:\n" + Arrays.toString(favNames));
break;
}
i++;
}
This is the error code I get:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: variable i
location: class JavaApplication13
at JavaApplication13.main(JavaApplication13.java:52)
Java Result: 1
I tried moving the first parts of the code inside the loop but it only prints one of the names the user enters.
//These parts:
String[] favNames = new String[i];
int i = 1;
If I swap the places between the first and second line. The array gets only 1 entry from the user.
//Only gets one entry
int i = 1;
String[] favNames = new String[i];