Java 我的程序在没有扫描字符串的情况下终止
当我执行代码时,我的程序在不扫描字符串的情况下终止Java 我的程序在没有扫描字符串的情况下终止,java,java.util.scanner,Java,Java.util.scanner,当我执行代码时,我的程序在不扫描字符串的情况下终止 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
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
用户输入最好如下所示:
-光标在此-num1换行符
num2新线
操作员换行符
如果执行多个nextDouble()
调用,程序将首先读取一个double
num1-光标在此-换行符
num2新线
操作员换行符
然后,用户必须键入enter以提交输入,这样第二个nextDouble()
就找不到要读取的内容,因为光标后面没有数字。它需要一个nextLine()
来吸收换行符
不幸的是,您在错误的位置有一个nextLine()
,它吸收了换行符
num1新线
-光标在此-num2换行符
操作员换行符
因此,您的程序在第一个nextDouble()
中吸收了双精度,在第二个nextLine()
中没有吸收任何内容,在nextLine()中吸收了换行符
要解决此问题,请在每个nextDouble()
的后面放置一个scan.nextLine()
。您不必读取nextLine()
调用的任何内容,除了有操作符的调用。您是否使用了scan.next()
?与Scanner.nextDouble()
相同的行为,如上问题所述。添加一个额外的scan.nextLine()
befores=scan.nextLine()代码>.yes使用scan.next()可以工作,但是为什么scan.nextline()不能工作,因为它也可以扫描字符串…另请参见