[英]Why do I get equals() == false when reading 2 seemingly identical Strings using a Scanner with next() and nextLine()?
我正在做一个基本的计算器。 当我尝试比较Strings并使用next()
,它可以正常工作,但是,如果我使用nextLine()
,则它不起作用。 怎么会这样? next
和nextLine
实际上不是一回事,只是一个跳过了一行而没有跳过了吗?
这是我的代码:
import java.util.Scanner;
class apples{
public static void main(String args[]){
Scanner Max = new Scanner(System.in);
int num1, num2, answer;
String plumi;
System.out.println("enter your first number");
num1 = Max.nextInt();
System.out.println("enter your second number");
num2 = Max.nextInt();
System.out.println("enter if you want to use plus or minus");
plumi = Max.next();
if(plumi.equals("plus")){
answer = num1 + num2;
System.out.println("the answer is " + answer);
}
if(plumi.equals("minus")){
answer = num1 - num2;
System.out.println("the answer is " + answer);
}
}
}
他们不一样。
next()
和nextInt()
方法首先跳过与定界符模式匹配的所有输入,然后尝试返回下一个标记。 nextLine()
方法返回当前行的其余部分。
例如,如果输入为"123\\nplus\\n"
,则对nextInt()
的调用将消耗123
,而\\n
处于等待状态。
此时,对next()
的调用将跳过\\n
,然后消耗plus
,而最后一个\\n
处于等待状态。 或者,对nextLine()
的调用将消耗\\n
并返回一个空字符串作为该行,从而使plus\\n
处于等待状态。
如果您希望在使用next()
或nextInt()
nextLine()
之后使用nextLine()
,则答案是向nextLine()
插入另一个调用,以刷新剩下的换行符。
尝试使用以下代码代替您的代码:
if(plumi.equals("plus")){
answer = num1 + num2;
System.out.println("the answer is " + answer);
}
else if(plumi.equals("minus")){
answer = num1 - num2;
System.out.println("the answer is " + answer);
}
else {
System.out.println(plumi);
}
然后尝试输入以下内容:
1 //press enter
2 plus //press enter
看看会发生什么,您会明白的。
一个起作用而另一个不起作用的原因是……嗯,它们不是同一回事。 它们都存在于稍微不同的用例中。
比较next()
和nextLine()
- nextLine()
期望行分隔符终止,我认为您没有输入。 但是,文档注释建议即使没有终止行分隔符,它也应该可以工作,因此,您必须进行调试才能找出它为什么会中断的确切原因。
乍一看,您的代码应该可以工作。 要查看为什么它不起作用,您必须对其进行调试。 如果您还不知道如何使用调试器,请使用“穷人调试器”:
System.out.println("enter if you want to use plus or minus");
plumi = Max.next();
System.out.println("You entered ["+plumi+"]"); // poor man's debugger
我用[]
引用值,因为它们很少是我要打印的值的一部分,并且当有其他意外的空格(例如[ plumi]
或[plumi ]
)时,它更易于查看。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.