问题
Why scanner is not taking input of another string and skepping it? I cant understand, here is my code:
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String name;
String address;
int age;
System.out.println("Enter your name");
name = s.nextLine();
System.out.println("My name is :" + name);
System.out.println("Enter your age");
age = s.nextInt();
System.out.println("My age is :" + age);
System.out.println("Enter your address");
address = s.nextLine();
System.out.println("My address is :" + address);
}
}
Output :
Enter your name
dk
My name is :dk
Enter your age
22
My age is :22
Enter your address
My address is :
回答1:
It is simple. You can use s.nextLine();
after the age = s.nextInt()
;
Scanner provides a method nextInt()
to request user input and does not consume the last newline character (\n
).
System.out.println("Enter your age");
age = s.nextInt();
s.nextLine(); // consumes the \n character
System.out.println("My age is :" + age);
回答2:
You should close the scanner after the last system out
回答3:
Place below statement after Statement.out.println("My age is",age);
s.nextLine();
Above statement will do flush, which will clear the cache location in order to accept new input.
来源:https://stackoverflow.com/questions/50675707/scanner-is-not-taking-input-of-another-string-and-skipping-it