我是Java的新手,似乎无法找到我的问题的答案。 我不确定我是否正确地嵌套循环。 " while循环"在"里面做什么"必须在人没有输入时执行"是"或"否"对于以下问题:
input = JOptionPane.showInputDialog("Do you have more grades to input? Please type 'Yes' or 'No'.");
但事实证明,如果我输入"是"或"否"循环仍在执行中。 如果有人能指出我做错了什么我会很感激! "
String input;
int grade;
do {
input = JOptionPane.showInputDialog("Enter the midterm grades, please");
grade = Integer.parseInt(input);
if ( grade < 0 || grade > 100 ) {
input = JOptionPane.showInputDialog("You have entered an invalid grade. The grade should be a number between 0 and 100. Enter the midterm grades, please.");
grade = Integer.parseInt(input);
}
input = JOptionPane.showInputDialog("Do you have more grades to input? Please type 'Yes' or 'No'.");
while ( (!input.equals("Yes")) || (!input.equals("No")) ) {
input = JOptionPane.showInputDialog("You should type 'Yes' if you want to input more grades or 'No' if you are done with inputing grades. Do you have more grades to input? Please type 'Yes' or 'No'.");
if ( (input.equals("Yes")) || (input.equals("No")) ) {
break;
} else {
continue;
}
}
} while ( input.equals("Yes") );
答案 0 :(得分:1)
看起来像这样:
while ( (!input.equals("Yes")) || (!input.equals("No")) ) {
应该像这样更改为&&
:
while ( (!input.equals("Yes")) && (!input.equals("No")) ) {
答案 1 :(得分:0)
你的条件错了
( (!input.equals("Yes")) || (!input.equals("No")) )
当输入为“是”时,评估结果为:
! true || ! false
哪个是真的,所以循环继续!
你想要的可能是
while ( (! input.equals("Yes")) && (! input.equals("No")) )
答案 2 :(得分:0)
您应该从&&
更改为||
,即。你应该迭代,如果输入不同于&#34;是&#34; 和不同于&#34;否&#34;
您可以将代码重写为:
while (!input.equals("Yes") && !input.equals("No") ) {
input = JOptionPane.showInputDialog("You should type 'Yes' if you want to input more grades or 'No' if you are done with inputing grades. Do you have more grades to input? Please type 'Yes' or 'No'.");
}
答案 3 :(得分:0)
String input = null;
int grade = 0; // local variables don't initlized by default value in function, only class fields
int counter = 0;
do {
counter++;
do{
grade = Integer.parseInt(JOptionPane.showInputDialog("Enter the midterm grades grade for " + counter + " student must be between 0-100 : , please"));
}while(grade < 0 || grade > 100); // promot user again if it enters data in wrong range till , he/she don't input correct value
input = JOptionPane.showInputDialog("If you want to Enter more grades then type 'Y' or 'Yes' .. ");
} while ( (input.toLowerCase()).equals("yes") || (input.toLowerCase()).equals("y")); // lower case because some users will type like "YEs" or something, can also use EqualsIgnoreCase function
不知道为什么你写了太多的行:),谢谢:) ,,评论如果有任何错误我没有检查并且没有在java编写程序最近2年:p,并且还添加了一个设施,你促进bel ike,为学生1,2..n等输入grande,你也可以删除,如果你不想要:))