Java 让我的while循环工作有困难
我目前正在为一个班级做这个作业,我很难让我的while循环正常工作。有人能帮我弄清楚为什么我不能让用户输入y或n来重新启动循环或终止循环吗?非常感谢你Java 让我的while循环工作有困难,java,loops,while-loop,Java,Loops,While Loop,我目前正在为一个班级做这个作业,我很难让我的while循环正常工作。有人能帮我弄清楚为什么我不能让用户输入y或n来重新启动循环或终止循环吗?非常感谢你 import java.util.Scanner; import java.text.NumberFormat; public class EvenQuizzes { public static void main (String[] args) { String another="y"; double percen
import java.util.Scanner;
import java.text.NumberFormat;
public class EvenQuizzes {
public static void main (String[] args) {
String another="y";
double percent;
int answers;
int score = 0;
Scanner scan = new Scanner(System.in);
NumberFormat fmt = NumberFormat.getPercentInstance();
// Asks the user to input the amount of questions on the quiz
System.out.print("How many questions are on the quiz? ");
final int QUESTIONS = scan.nextInt();
System.out.println(); // spacer
int[] key = new int [QUESTIONS];
// Asks the user to enter the key
for (int i=0; i<key.length; i++){
System.out.print("Enter the correct answer for question "+ (i+1) +": ");
key[i] = scan.nextInt();
}
System.out.println(); // spacer
while (another.equalsIgnoreCase("y")) {
// Asks the user to enter their answers
for (int i=0; i<key.length; i++) {
System.out.print("Student's answer for question " + (i+1) + ": " );
answers = scan.nextInt();
if (answers == key[i])
score++;
}
// Grades the amount of questions right and gives the percentage
percent = (double)score/QUESTIONS;
System.out.println();
System.out.println("Your number of correct answers is: " + score);
System.out.println("Your quiz percentage: " + fmt.format(percent));
System.out.println();
System.out.println("Grade another quiz? (y/n)");
another = scan.nextLine();
}
}
}
import java.util.Scanner;
导入java.text.NumberFormat;
公开课测验{
公共静态void main(字符串[]args){
字符串另一个=“y”;
百分之二;
int答案;
智力得分=0;
扫描仪扫描=新扫描仪(System.in);
NumberFormat fmt=NumberFormat.getPercentInstance();
//要求用户输入测验中的问题数量
System.out.print(“测验中有多少问题?”);
final int QUESTIONS=scan.nextInt();
System.out.println();//间隔符
int[]键=新int[问题];
//要求用户输入密钥
对于while循环末尾的(int i=0;i),请尝试添加以下打印语句:
System.out.println("Next line is >>>" + another + "<<<");
System.out.println(“下一行是>>>”+另一行+”,所以不是这个
for (int i=0; i<key.length; i++) {
System.out.print("Student's answer for question " + (i+1) + ": " );
answers = scan.nextInt();
if (answers == key[i])
score++;
}
for(int i=0;i这与您的扫描在从用户获取y/n之前读取整数有关
在此转换中,扫描读取的是一个换行符而不是y。因此,另一个是换行符,因此无法满足while循环条件
为了克服这个问题,快捷方式就是@3kings所提到的。
另一种方法是将所有输入扫描为字符串(nextLine),然后对测验部分进行整数解析。这似乎需要做很多工作,但您可以使用parseInt和try/catch exception。您是否尝试在另一个=scan.nextLine()之后打印另一个;
-它可能有“\n”,因此它不等于(“y”)
-您可以将while表达式更改为startsWith()
。您需要在语句answers=scan.nextInt();
之后放置一个scan.nextLine()properly@3kings请随意将此作为答案发布。
for (int i=0; i<key.length; i++) {
System.out.print("Student's answer for question " + (i+1) + ": " );
answers = scan.nextInt();
if (answers == key[i])
score++;
}
scan.nextLine();