I am trying to have a user input an int
and then input that number of names.
The program prints those names backwards and in reverse order. However, the array where I am storing these names is always being created one element too small when I use Scanner
. When I just assign a number myself, I don't have this problem. Is there something unique with Scanner
or what am I doing wrong?
import java.util.Scanner;
class forTester {
public static void main (String str[]) {
Scanner scan = new Scanner(System.in);
//Why does this commented code scan only one less name than expected???
/*
System.out.println("How many names do you want to enter?");
int num = scan.nextInt();
System.out.println("Enter " + num + " Names:");
String names[] = new String[num];
*/
//Comment out the next two lines if you use the four lines above.
System.out.println("Enter " + 4 + " Names:");
String names[] = new String[4];
// The code below works fine.
for (int i = 0; i < names.length; i++) {
names[i]=scan.nextLine();
}
for(int i = names.length - 1; i >= 0; i--) {
for(int p = names[i].length() - 1; p >= 0; p--) {
System.out.print(names[i].charAt(p));
}
System.out.println("");
}
}
}