下面的代码是我到目前为止所写的,所以没有实现。但是在程序中它会询问用户是否丢弃了最低等级。如果用户回答说“是”,“是”,“否”或“否”,则应该结束do循环并继续执行其余代码。
然而,即使我输入了正确的响应,它也会继续循环。我是一个非常新的java,所以如果这真的很愚蠢,请道歉。
代码:
import java.util.Scanner;
public class AvgGrade {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int numTest=1;
//Test Number Checker
while(numTest<=1) {
System.out.println("How many tests were given out");
System.out.println("Must be more than 1");
numTest=input.nextInt();
}
//Lowest Grade Dropped Checker
boolean droppedLow=false;
String dropAnswer="default";
do{
System.out.println("Is the lowest grade dropped?");
System.out.println("Answer: Yes, yes, No, no");
dropAnswer=input.next();
}
while(dropAnswer.compareTo("Yes")!=0||dropAnswer.compareTo("yes")!=0||
dropAnswer.compareTo("No")!=0||dropAnswer.compareTo("no")!=0);
if(dropAnswer.equals("Yes")||dropAnswer.equals("yes"))
droppedLow=true;
else if(dropAnswer.equals("No")||dropAnswer.equals("no"))
droppedLow=false;
System.out.println("----------------DEBUG----------------");
System.out.println(numTest);
System.out.println(dropAnswer);
System.out.println(droppedLow);
}
}
控制台/输出:
How many tests were given out
Must be more than 1
5
Is the lowest grade dropped?
Answer: Yes, yes, No, no
Yes
Is the lowest grade dropped?
Answer: Yes, yes, No, no
yes
Is the lowest grade dropped?
Answer: Yes, yes, No, no
no
Is the lowest grade dropped?
Answer: Yes, yes, No, no
No
Is the lowest grade dropped?
Answer: Yes, yes, No, no
答案 0 :(得分:1)
无论你键入什么,这都将是真的,所以循环将永远持续:
dropAnswer.compareTo("Yes")!=0||dropAnswer.compareTo("yes")!=0||
dropAnswer.compareTo("No")!=0||dropAnswer.compareTo("no")!=0
基本上,你的情况意味着“循环如果dropAnswer不等于'是'或它不等于'是'或它不等于'否'或者它不等于'不'。“至少有三个条件总是如此,因为没有字符串是'是','是','否'和'不'同时。
我认为您打算使用&&
(和)代替||
(或):
dropAnswer.compareTo("Yes") != 0 && dropAnswer.compareTo("yes") != 0 &&
dropAnswer.compareTo("No") != 0 && dropAnswer.compareTo("no") != 0