This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(19个回答)
6年前关闭。
当我执行代码时,我的程序将终止而不扫描字符串。
我的程序在
它怎么结束了?
(19个回答)
6年前关闭。
当我执行代码时,我的程序将终止而不扫描字符串。
double x, y;
String s;
Scanner scan = new Scanner(System.in);
System.out.println("Enter Number: ");
x = scan.nextDouble();
System.out.println("Enter Number 2: ");
y = scan.nextDouble();
System.out.println("Enter Operater: x,+,/,-");
s = scan.nextLine();
if(s.equals("x"))
{
System.out.print(x * y);
}
else if(s.equals("+"))
{
System.out.print(x + y);
}
else if(s.equals("/"))
{
System.out.print(x / y);
}
else if(s.equals("-"))
{
System.out.print(x - y);
}
scan.close();
我的程序在
s = scan.nextline();
之前结束它怎么结束了?
最佳答案
行尾您留在缓冲区中。next( )
从缓冲区读取令牌,直到下一个空格,而nextLine( )
最多读取\n
...
System.out.print("Enter Number 2: ");
y = scan.nextDouble();
System.out.print("Enter Operater: x,+,/,-");
s = scan.next();
...
Enter Number: 1
Enter Number 2: 2
Enter Operater: x,+,/,--
-1.0
10-08 20:09