【问题标题】:Java using multiple methods in the programJava在程序中使用多种方法
【发布时间】:2017-12-04 20:00:27
【问题描述】:

我在 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");
      }
   }
}

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

【问题讨论】:

  • 这个问题不适合 SO。也许codereview.stackexchange.com 会更好,但我不知道他们的接受标准是什么。现在,这个问题非常类似于“我如何用 Java 编写代码?”这对 SO 来说太宽泛了。如果这是功课,你应该咨询老师或同学。
  • @jdv:如果您不知道 Code Review 的接受标准是什么,甚至不要建议它。说真的,太多不合适的东西会流到那里,除非您确定,否则表明该网站只会导致更多不合适的东西流到那里。
  • 我不清楚你为什么要在这里使用多种方法。这似乎包含良好且清晰,即使它在 main 中运行。
  • @Makoto 假装自己找不到代码审查是愚蠢的。我明确建议将其作为进一步研究的资源。这整个“不要提及其他 SE 网站”的事情是荒谬的。

标签: java oop methods


【解决方案1】:

您可以简单地将您的计算和用户输入封装在一个方法调用 multiplication() 中,如下面的代码所示。该方法将返回一个布尔值来识别用户是否正确回答了问题。 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;

  }

}

【讨论】:

  • 感谢您的帮助,但现在如果给出错误答案,程序不会再次重复相同的问题。
  • 我试过了,它确实重复了。可以再验证一下吗?
  • 我又贴了一遍,还是不行。我正在使用 Eclipse Mars 4.5.0。
  • 好的,重新复制代码。我对刚才的要求感到困惑。现在,如果答案错误,它应该重复相同的问题。
猜你喜欢
  • 1970-01-01
  • 2017-08-10
  • 2014-03-25
  • 2021-11-18
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多