为什么此循环无法正常运行

时间:2018-10-27 01:53:07

标签: java loops

我想编写一个Java程序,让我问用户他们想回答多少个数学问题,并使用选择的任何循环根据他们的回答生成随机问题,并保持对他们回答正确数量的计数。我得到它来生成随机数学问题,但只有在似乎跳过循环时才这样做。有人可以帮忙吗?

import javax.swing.JOptionPane;
import java.util.Random;
import java.util.Scanner;

/**
 *
 * @author user
 */
public class MathQuiz {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Random obj = new Random();
        int num1 = obj.nextInt(10);
        int num2 = obj.nextInt(10);
        int rand = num1 + num2;
        String response = JOptionPane.showInputDialog(null,"How many problems would you like to solve?");
        int ans = Integer.parseInt(response); // answer from question
        String result= null;
        int times = input.nextInt();
        int counter = 0; //counts total math problems

        while (counter != ans){
            counter++;
            JOptionPane.showInputDialog(num1 + "+" +num2);
            if (ans == rand){
                result= "Correct";
            }else {
                result= "Incorrect";
            }
        }   JOptionPane.showMessageDialog(null, );

        }
}  

2 个答案:

答案 0 :(得分:0)

这是您的代码中的问题: 计算值后,您不会显示结果。 并非每次都生成随机数。

usr/bin/ld: /software/packages/lib/libbz2.a(bzlib.o): relocation R_X86_64_32S against .text' can not be used when making a shared object; recompile with -fPIC /software/packages/lib/libbz2.a: could not read symbols: Bad value

答案 1 :(得分:0)

在循环中获取的数字不应与在while(...)条件中使用的数字存储在同一变量中。在这种情况下,您使用了ans。在下面的示例中,我为数学答案和在循环中迭代的次数提供了单独的变量。您遇到的另一个问题是您没有将结果消息传递给showMessageDialog(..)方法。

import javax.swing.JOptionPane;
import java.util.Random;
import java.util.Scanner;

public class MathQuiz {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Random obj = new Random();
        String timesString = JOptionPane.showInputDialog(null,"How many problems would you like to solve?");
        int timesInt = Integer.parseInt(timesString); // answer from question
        int counter = 0; //counts total math problems

        while (counter != timesInt) {
            counter++;

            int num1 = obj.nextInt(10);
            int num2 = obj.nextInt(10);
            int rand = num1 + num2;

            String answerString = JOptionPane.showInputDialog(num1 + "+" +num2);
            int answerInt = Integer.parseInt(answerString);

            JOptionPane.showMessageDialog(null, answerInt == rand ? "Correct" : "Incorrect");
        }
    }
}