非常简单的代码,如果我将字符串K更改为“ Bye”,则会收到错误消息,只有if else结构有效,而if else if else不起作用。请帮助我理解原因。
public static void main(String [] args){
String k = "Hi";
Scanner scnr = new Scanner(k);
if (scnr.next().equals("Hi")){
System.out.println("Yes");
}
else if (scnr.next().equals("Bye")){
System.out.println("No");
}
else {
System.out.println("Maybe");
}
}
答案 0 :(得分:2)
您应该将“下一个”结果保存在变量中,因为每次调用next时,您都会尝试获取下一个元素。 (https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next())。您可以使用hasNext检查下一个。 (https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNext())
public static void main(String [] args){
String k = "Hi";
Scanner scnr = new Scanner(k);
String read = scnr.next();
if (read.equals("Hi")){
System.out.println("Yes");
}
else if (read.equals("Bye")){
System.out.println("No");
}
else {
System.out.println("Maybe");
}
}
答案 1 :(得分:1)
每次使用next()
时,您都会继续进行迭代,在这种情况下,不存在需要进一步迭代的项目,因此请执行以下操作:
public static void main(String [] args){
String k = "Bye";
Scanner scnr = new Scanner(k);
String element = scnr.next();
if (element.equals("Hi")){
System.out.println("Yes");
} else if (element.equals("Bye")){
System.out.println("No");
} else {
System.out.println("Maybe");
}
}
在这种情况下,如果您不进行环回,则您只有1次呼叫next()
的时间。
答案 2 :(得分:0)
每当您从Scanner实例调用next()方法时,它都会移动(换句话说,它会为您提供元素并继续前进。
在特定示例中,发生了以下情况:
public static void main(String [] args){
String k = "Bye";
Scanner scnr = new Scanner(k); // scnr is at the start of string k
if (scnr.next().equals("Hi")){ // scnr gives you "Bye" here;
// you compare it with constant "Hi" and
// throw away that variable;
System.out.println("Yes");
}
else if (scnr.next().equals("Bye")){ // here scnr is at the end of string k
// therefore, it can't give you next element
System.out.println("No");
}
else {
System.out.println("Maybe");
}
}
以下是纠正此问题的方法:
public static void main(String [] args){
String k = "Hi";
Scanner scnr = new Scanner(k);
String myNextElement = scnr.next();
if (myNextElement.equals("Hi")){
System.out.println("Yes");
}
else if (myNextElement.equals("Bye")){
System.out.println("No");
}
else {
System.out.println("Maybe");
}
}