循环循环和If语句?

时间:2017-11-28 23:28:34

标签: java arrays loops if-statement

我是初学者编程,我想用数组问多个问题并告诉用户他是否对每个问题都是对或错,我设法让它运行,但现在我如何实现代码以便用户只会有3次尝试才能正确回答问题。

for(int n = 0; n <QArray.length; n++)
{
    System.out.println("Question" + (n+1));
    System.out.println(QArray[n]);

    String ans = scanner.nextLine();

    if (ans.equalsIgnoreCase(AArray[n]))
    {
        System.out.println("That is correct!");
    }
    else   
    {     
        System.out.println("That is incorrect!");
    }
}

2 个答案:

答案 0 :(得分:0)

因此,如果我正确理解了您的目标,那么您就会有一系列问题,虽然他们对这些问题的尝试次数少于三次,但您希望用户能够尝试回答这些问题吗?

使用您现有的样式,您可以执行类似

的操作
for(int n = 0; n < QArray.length; n++)
{
    System.out.println("Question" + (n+1));
    System.out.println(QArray[n]);

    int incorrectAnswers = 0;
    while(incorrectAnswers < 3)
    {
        String ans = scanner.nextLine();
        if (ans.equalsIgnoreCase(AArray[n]))
        {
            System.out.println("That is correct!");
            break;
        }
        else   
        {     
            System.out.println("That is incorrect!");
            incorrectAnswers++;
        }
    }
}

根据数据的显示和传输方式以及与安全性等相关的问题,可以更轻松地管理代码,以获得包含问题和答案的QuestionAnswer对象,以及构成有效答案的方法(例如,不区分大小写,或者您可能希望接受多个单词等,无论哪种情况适用于您的情况),因此您最终可能会得到如下所示的代码。

for(int i = 0; i < questionAnswerArray.length; i++)
{
    QuestionAnswer qa = questionAnswerArray[i];

    System.out.println("Question " + (i+1));
    System.out.println(qa.getQuestion());

    int incorrectAnswers = 0;
    while(incorrectAnswers < 3)
    {
        String ans = scanner.nextLine();
        if (qa.isValidAnswer(ans))
        {
            System.out.println("That is correct!");
            break;
        }
        else   
        {     
            System.out.println("That is incorrect!");
            incorrectAnswers++;
        }
    }
}

答案 1 :(得分:-1)

在第一个循环中加入第二个循环。

for(int n = 0; n < QArray.length; n++) {
  boolean correct = false;
  for(int m = 0; m < 3; m ++) {
    String ans = scanner.nextLine();
    if (ans.equalsIgnoreCase(AArray[n])) {
      System.out.println("That is correct!");
      correct = true;
      break;
    } else {     
      System.out.println("That is incorrect!");
    }
  }
  if(!correct) {
    //something
  } else {
    //something else
  }
}

请注意break;。当提交正确答案时,该命令将退出内部for循环(包含扫描仪输入)。如果用户在3次尝试中没有得到正确答案,则for循环将在到达其计数器末尾时结束。

相关问题