如何将nextLine()与字符串进行比较
我在APCS类中有一项任务,要求我们创建组合锁,并且我认为我已经完成了基本结构。但是,我一直遇到一个问题,它不会让我比较原始的nextLine()
和String
。如何将nextLine()与字符串进行比较
我想知道nextLine()
是默认的int
s?或者任何人都可以告诉我我的代码有什么问题?
if((in.nextLine()).compareTo(combo))
{
System.out.println("The lock is now unlocked.");
System.out.println("Please enter the combo to unlock: ");
if((in.nextLine()).compareTo(combo))
{
System.out.println("The lock is now locked.");
}
else
{
System.exit(0);
}
}
P. IDE将返回错误:“错误:不兼容的类型:int不能转换为布尔值”并且指的是如果资格。
nextLine()
将始终返回一个字符串,所以这不是你的问题。
compareTo(str)
返回一个负数如果str
字典顺序是小于该值被比较于0,如果字符串是字典顺序相等,或者如果str
的正数是字典顺序大于值多的被比较。
你想使用equals(str)
,它返回一个布尔值。
你的问题是,compareTo()返回一个整数值,而不是布尔值。
见的compareTo了Java API文档(接口相媲美,在http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html):
Method Detail
compareTo
Returns: a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
比较两个字符串的最简单的方法是使用
if (in.nextLine().equals(combo)) { /* code here */ }
当心另一个陷阱中这个节目也是。你的第一个nextLine()和你的第二个nextLine()实际上是两个单独的输入行。 nextLine()返回来自阅读器的下一行输入,因此每次调用它时都会返回不同的输入行。一种解决方案是将nextLine()的结果保存为变量:
String enteredCombo = in.nextLine();
if (enteredCombo.equals(combo))
{
System.out.println("The lock is now unlocked.");
System.out.println("Please enter the combo to lock: ");
enteredCombo = in.nextLine();
if(enteredCombo.equals(combo))
{
System.out.println("The lock is now locked.");
}
else
{
System.exit(0);
}
}
谢谢,那是问题所在,它现在可行。 – 2014-10-19 04:42:47