Java在程序中使用多种方法

时间:2017-12-04 20:00:27

标签: java oop methods

我在Java上有以下代码现在工作正常,但我想知道如何使用多种方法(面向对象编程)制作相同的程序。现在所有代码都在main方法中,我想做到这一点,因此它至少有一个其他方法进行计算,并且该方法将在main方法中调用。 该程序向用户询问不同类型的乘法问题,如2 * 3,9 * 5等等

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

public class Main {

  public static void main(String[] args) {

    Random number = new Random();

    while (true) {

        int nmb1 = number.nextInt(10) + 1;
        int nmb2 = number.nextInt(10) + 1;
        int multi = nmb1 * nmb2;
        int question;

        // read the user's input ...
        do {
            question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + nmb1 + "*" + nmb2));

            if (question != multi) {
                JOptionPane.showMessageDialog(null, "Wrong, try again");
            }
        }
        while (question != multi);
        // .. and repeat until the user types the correct answer

        JOptionPane.showMessageDialog(null, "Right");
      }
   }
}

如果有人能提供任何帮助,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以在方法调用乘法()中简单地包含计算和用户输入,如下面的代码所示。该方法将返回一个布尔值,以确定用户是否正确回答了问题。 HTH。

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

public class Main{

  public static void main(String[] args) {

      boolean correctAnswer;
      Random number = new Random();
      int nmb1;
      int nmb2;
      int multi;


    while (true) {
        nmb1 = number.nextInt(10) + 1;
        nmb2 = number.nextInt(10) + 1;
        multi = nmb1 * nmb2;

        // read the user's input ...
        do {
            correctAnswer = multiplication(nmb1,nmb2,multi);
        }
        while (correctAnswer != true);
        // .. and repeat until the user types the correct answer

        JOptionPane.showMessageDialog(null, "Right");
      }
   }


  public static boolean multiplication(int number1,int number2,int answer)
  {

      int question;

         question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + number1 + "*" + number2));

          if (question != answer) {
              JOptionPane.showMessageDialog(null, "Wrong, try again");

              return false;
          }

      return true;

  }

}