【发布时间】:2015-10-29 00:38:59
【问题描述】:
我目前正在为一堂课完成这项作业,我很难让我的 while 循环正常工作。谁能帮助我弄清楚为什么我不能让用户输入 y 或 n 来重新启动循环或终止循环?非常感谢!
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();
}
}
}
【问题讨论】:
-
您是否尝试过在
another = scan.nextline();之后打印another- 它可能有“\n”,所以它没有equal("y")- 您可以将您的while 表达式更改为startsWith()。跨度> -
您需要在您的声明
answers= scan.nextInt();之后放置一个scan.nextLine()以使您的代码正常工作 -
@3kings 随意发布这个作为答案。
标签: java loops while-loop