无法让我的while循环工作

时间:2015-10-29 00:39:00

标签: 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 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();

      }           
   }
}  

3 个答案:

答案 0 :(得分:1)

在while循环结束时,尝试添加此print语句:

System.out.println("Next line is >>>" + another + "<<<");

这应该清楚你从scan.nextLine()调用中获得了什么。它不会解决您的问题,但它会使问题变得明显。

答案 1 :(得分:1)

所以不是这个

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<key.length; i++) {
      System.out.print("Student's answer for question " + (i+1) + ": " );
      answers = scan.nextInt();

      if (answers == key[i])  
         score++;    
      }
    scan.nextLine();

答案 2 :(得分:0)

这与你的扫描在从用户获得y / n之前读取整数有关。

在此转换中,扫描正在读取换行符而不是y。结果,另一个是换行符char,因此失败了while循环条件。

为了解决这个问题,快捷方法是@ 3kings提到的。 另一种方法是将所有输入扫描为字符串(nextLine),然后为测验部分扫描整数。这可能看起来很多,但你可以使用parseInt并尝试/捕获异常。