I am learning Java, and I'm not very far into it, and I don't know why but Java seemed to skip a line. I don't think the code from all my pages is really neccesery so I will just put the first page and the result I get when using it. Thanks!
import java.util.Scanner;
public class First {
public static void main(String args[]){
Scanner scanz = new Scanner(System.in);
System.out.println("Hello, please tell me your birthday!");
System.out.print("Day: ");
int dayz = scanz.nextInt();
System.out.print("Month: ");
int monthz = scanz.nextInt();
System.out.print("Year: ");
int yearz = scanz.nextInt();
System.out.println("Now, tell me your name!");
System.out.print("Name: ");
String namez = scanz.nextLine();
Time timeObject = new Time(dayz,monthz,yearz);
Second secondObject = new Second(namez,timeObject);
System.out.println("\n\n\n\n\n" + secondObject);
}
}
It skips the line
String namez = scanz.nextLine();
Console output: (excuse the birthday bit, it is other stuff)
Hello, please tell me your birthday!
Day: 34
Month: 234
Year: 43
Now, tell me your name!
Name:
My name is and my birthday is 00/00/43
It doesn't give you a chance to give a name, it just skips straight past and takes the name as null. Please, if anyone could, tell me why! I want to learn Java, and this little annoyance is standing in my way.
Thanks!
解决方案
The problem is that the nextLine gets any characters on the line, and the \n (newline character) is left over from the scanner inputs above.
So instead of letting you enter something new, it takes the \n as the input and continues.
To fix, just put two scanners back to back like this:
System.out.print("Name: ");
scanz.nextLine();
String namez = scanz.nextLine();
Just using:
String namez = scanz.next();
will work too, but will limit the names to be one word. (aka first name only)