麻烦允许用户选择多个选项

时间:2018-02-06 01:46:50

标签: java for-loop

我正在尝试创建一个程序,在状态的大写上测试用户(我只包括5个状态,我会在其工作时添加其余的状态)。我无法使用代码向用户询问他们想要回答多少问题。当程序执行时,用户输入了他们想要回答的问题数量,它会在继续之前自动给出第一个问题和答案。我该如何解决?

 import java.util.Scanner;

public class lab1 
{
   public static void main(String[] args)
   { 
      //Create scanner object
      Scanner input = new Scanner(System.in);

      //Ask the user how many questions he/she would like to be asked

  System.out.println("How many questions would you like?");
      int numQuest = input.nextInt();

      //Store the 50 states and their capitals in a two-dimensional array
      String[][] states = {{"Alabama", "Montgomery"},
                           {"Alaska", "Juneau"},
                           {"Arizona", "Phoenix"},
                           {"Arkansas", "Little Rock"},
                           {"New York", "Albany"}
                           };

      //Create a for loop that asks a different question every loop
      for(int i = 0; i <= numQuest; i++)
      {
         System.out.print("What is the capital of " + states[i][0] + "? ");//Asks user question
         String answer = input.nextLine();//Allows user to answer

         //If statement determines whether or not answer is correct
         if(answer.equals(states[i][1]))
         {
            System.out.println("Your answer is correct.");
         }else
            System.out.println("The correct answer is " + states[i][1] + ".");

      }

   }

}

1 个答案:

答案 0 :(得分:0)

只需在input.nextLine();

之后添加int numQuest = input.nextInt();即可
import java.util.Scanner;

public class lab1 
{
   public static void main(String[] args)
   { 
      //Create scanner object
      Scanner input = new Scanner(System.in);

      //Ask the user how many questions he/she would like to be asked

      System.out.println("How many questions would you like?");
      int numQuest = input.nextInt();
      input.nextLine();
      //Store the 50 states and their capitals in a two-dimensional array
      String[][] states = {{"Alabama", "Montgomery"},
                           {"Alaska", "Juneau"},
                           {"Arizona", "Phoenix"},
                           {"Arkansas", "Little Rock"},
                           {"New York", "Albany"}
                           };

      //Create a for loop that asks a different question every loop
      for(int i = 0; i <= numQuest; i++)
      {
         System.out.print("What is the capital of " + states[i][0] + "? ");//Asks user question
         String answer = input.nextLine();//Allows user to answer

         //If statement determines whether or not answer is correct
         if(answer.equals(states[i][1]))
         {
            System.out.println("Your answer is correct.");
         }else
            System.out.println("The correct answer is " + states[i][1] + ".");

      }

   }

}