-1

我们应该在我们的程序中使用方法,但我无法将它们合并到其中。我的程序就像一个数学游戏,询问简单的加法和加法/减法问题。我希望所有计算都在方法中,但我无法返回整个方程。

当涉及到我需要去的方向时,我需要一些帮助,以便在我的程序中有效地使用方法,以及我应该在哪里进行计算!以及它自己的方法中应该有什么以及主要方法中应该有什么。

import javax.swing.*;
import java.io.*;


public class SummativeTwo {

  public static void main (String[] args) throws IOException {

    BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in)); {

      Object[] options = {"Yes! I'm Excited!","Im kind of nervous..","Now Way! Ewww!"};
      int n = JOptionPane.showOptionDialog(null, "Welcome Million Dollar Madness! "+ "Are you ready to play?","Welcome",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,null,options,options[2]);
      if (n == JOptionPane.YES_OPTION) {
        JOptionPane.showMessageDialog(null,"Okie Dokie! Lets get started!", "Okie Dokie", JOptionPane.INFORMATION_MESSAGE);
      }
      if (n == JOptionPane.NO_OPTION) {
        JOptionPane.showMessageDialog(null,"Aw thats okay! Im sure you'll have fun!", "It's okay", JOptionPane.INFORMATION_MESSAGE);
      }
      if (n == JOptionPane.CANCEL_OPTION) {
        JOptionPane.showMessageDialog(null,"Well too bad so sad! You're going to have to play anyways!", "Too bad so sad", JOptionPane.INFORMATION_MESSAGE);
      }

      Object[] optionsA = {"Yes Please", "Nope! I'm good!"};
      int x = JOptionPane.showOptionDialog(null,"Would you like to know the instructions for this game?","INSTRUCTIONS?", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,optionsA,optionsA[0]); 
      if (x == JOptionPane.YES_OPTION) {
        JOptionPane.showMessageDialog(null,"There will be 3 levels in this game. As you go farther, the questions get harder and harder and each question \n. Each time you get a question right you will recieve a certain amount of money, which increases each time you pass each question. \n But be careful, because if you get 3 questions wrong in one level \n it's GAME OVER for you! Meaning you lose all your money. \n You may Cash Out at any point if you're not willing to risk losing the amount of money you have. Reach the end of \n the 3 levels and you take home all your money! \n GOOD LUCK!", "Instructions", JOptionPane.INFORMATION_MESSAGE);
      }
      if (x == JOptionPane.NO_OPTION) {
        JOptionPane.showMessageDialog(null,"Suit Yourself! Lets Start!", "Your Choice", JOptionPane.INFORMATION_MESSAGE);
      }
      JOptionPane.showMessageDialog(null,"Welcome to Level: 1 " ," level 1", JOptionPane.INFORMATION_MESSAGE);

      //LEVEL ONE
      int wrong = 0;
      int run = 1;
      int questionnum = 0;
      int amount = 0;

      while (run <= 6 && wrong != 3)
      {
        run ++;
        questionnum++;
        int increment = 150;
        amount += 150;

        int numOne = additionOne ();
        int numTwo = additionTwo ();
        int answer = numOne + numTwo;


        String useranswerA = JOptionPane.showInputDialog(null,"Question #" + questionnum + " is for: $" + increment + "\n" + numOne + " + " + numTwo + " = ?", "Question", JOptionPane.INFORMATION_MESSAGE);
        int useranswer = Integer.parseInt(useranswerA);

        if (useranswer != answer)
        {
          wrong ++;
          JOptionPane.showMessageDialog(null,"You got the wrong answer! \n The correct answer is: " + answer + " \n Questions Wrong: " + wrong, "Wrong Answer", JOptionPane.INFORMATION_MESSAGE);
          int y = JOptionPane.showOptionDialog(null,"CASH OUT with a total of $" + amount + "?","Cash Out?", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,optionsA,optionsA[0]);
          if (y == JOptionPane.YES_OPTION) {
            JOptionPane.showMessageDialog(null,"Thanks for Playing!", "Thank You!", JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);
          }
          if (y == JOptionPane.NO_OPTION) {}
        }
        else if (useranswer == answer)
        {
          JOptionPane.showMessageDialog(null,"Correct!", "Right Answer", JOptionPane.INFORMATION_MESSAGE);
          int y = JOptionPane.showOptionDialog(null,"CASH OUT with a total of $" + amount + "?","Cash Out?", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,optionsA,optionsA[0]);
          if (y == JOptionPane.YES_OPTION) {
            JOptionPane.showMessageDialog(null,"Thanks for Playing!", "Thank You!", JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);
          }
          if (y == JOptionPane.NO_OPTION) {}
        }
      }
      JOptionPane.showMessageDialog(null,"LEVEL ONE COMPLETE!", "LEVEL 1", JOptionPane.INFORMATION_MESSAGE);
      JOptionPane.showMessageDialog(null,"Cash on Hand: $ " + amount, "Cash", JOptionPane.INFORMATION_MESSAGE);


      //LEVEL TWO
      JOptionPane.showMessageDialog(null,"Welcome to Level: 2 " ," level 2", JOptionPane.INFORMATION_MESSAGE);
      int wrongB = 0;
      int runB = 1;
      int questionnumB = 0;


      while (runB <= 8 && wrongB != 3)
      {
        runB ++;
        questionnumB++;
        amount += 250;

        int increment = 250;

        int numOne = additionOne ();
        int numTwo = additionTwo ();
        int numThree = numThree ();
        int answer = numOne + numTwo - numThree;


        String useranswerA = JOptionPane.showInputDialog(null,"Question #" + questionnum + " is for: $" + increment + "\n" + numOne + " + " + numTwo + " - " + numThree + " = ?", "Question", JOptionPane.INFORMATION_MESSAGE);
        int useranswer = Integer.parseInt(useranswerA);

        if (useranswer != answer)
        {
          wrong ++;
          JOptionPane.showMessageDialog(null,"You got the wrong answer! \n The correct answer is: " + answer + " \n Questions Wrong: " + wrongB, "Wrong Answer", JOptionPane.INFORMATION_MESSAGE);
          int z = JOptionPane.showOptionDialog(null,"CASH OUT with a total of $" + amount + "?","Cash Out?", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,optionsA,optionsA[0]);
          if (z == JOptionPane.YES_OPTION) {
            JOptionPane.showMessageDialog(null,"Thanks for Playing!", "Thank You!", JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);
          }
          if (z == JOptionPane.NO_OPTION) {}
        }
        else if (useranswer == answer)
        {
          JOptionPane.showMessageDialog(null,"Correct!", "Right Answer", JOptionPane.INFORMATION_MESSAGE);
          int z = JOptionPane.showOptionDialog(null,"CASH OUT with a total of $" + amount + "?","Cash Out?", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,optionsA,optionsA[0]);
          if (z == JOptionPane.YES_OPTION) {
            JOptionPane.showMessageDialog(null,"Thanks for Playing!", "Thank You!", JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);
          }
          if (z == JOptionPane.NO_OPTION) {}
        }
      }
      JOptionPane.showMessageDialog(null,"LEVEL TWO COMPLETE!", "LEVEL 2", JOptionPane.INFORMATION_MESSAGE);
      JOptionPane.showMessageDialog(null,"Cash on Hand: $ " + amount, "Cash",JOptionPane.QUESTION_MESSAGE);

    }
  }

  public static int additionOne ()
  {
    int x = (int)( Math.random () * 30);
    return x;
  }
  public static int additionTwo ()
  {
    int x = (int)( Math.random () * 30);
    return x;
  }
  public static int numThree ()
  {
    int x = (int) (Math.random () * 15);
    return x;
  }
}
4

5 回答 5

1

程序设计的一般经验法则:

  • 如果您发现自己一遍又一遍地编写大量相同的代码,最好将这些代码放在自己的方法中。这样,更容易弄清楚发生了什么,如果您需要更改代码,您只需在一个地方进行更改。当您可以将事物划分为易于测试的方法时,它还可以更轻松地对代码进行单元测试。方法还允许您使用封装,例如可以将某些代码标记为私有或受保护。
  • 我喜欢让我的主要方法尽可能简单。理想情况下,它应该只是程序的入口点并启动真正的代码。我对此没有太多支持,但它有助于促进代码重用。main 方法本质上与启动它的命令行耦合;例如,如果要将桌面应用程序迁移到 Web 应用程序,则必须将其解耦。

在您的代码中,您有 2 个级别,每个级别的功能都非常相似。这可能是开始考虑将代码放入自己的方法的好地方。然后,如果您想添加级别 3,则不需要很多额外的代码。

于 2013-06-15T17:27:30.157 回答
0

首先,拉出任何重复的东西。所以对于 2 组块:

if (useranswer != answer)

else if (useranswer == answer)

我会让这些块的内容成为一种方法,其中任何差异都是该方法的参数 - 或者只有一个布尔正确/错误参数并调整方法内的哪一组字符串被调用。无论哪种方式代码更少。如果在集合 1 和 3 以及 2 和 4 中使用了相同的字符串,那么不要将它们作为参数发送 4 次(声明它们 4 次),只需声明它们两次 - 这意味着在方法内部。

删除重复代码后,下一步将从小代码块(可能 10-20 行)开始,通常在大括号内,并且最好使用其他地方不需要的新变量。

删除较小的块后,您可能会发现有新的“小”块可以删除。级别 1 和级别 2 可以采用不同的方法。

理想情况下,只是尽量保持方法更小,这样读者就不必滚动,他们可以轻松地查看方法的整个代码,在他们的脑海中运行它,并知道它在做什么。

于 2013-06-15T17:37:19.803 回答
0

你的问题太模糊了,但我认为这会对你有所帮助。

你有三个函数:additionOneadditionTwo它们numThree非常相似。您可以将它们简化为如下函数:

public static int myFunction(int multiplier)
{
    int x = (int)(Math.random () * multiplier);
    return x;
}

并像这样使用它:

int numOne = myFunction(30);
int numTwo = myFunction(30);
int numThree = myFunction(15);
int answer = numOne + numTwo - numThree;
于 2013-06-15T17:26:39.180 回答
0

编写方法的目的之一是减少重复代码。在您的代码中,您似乎需要多次调用 JOptionPange.showMessageDialog 。因此,您可以编写一个方法,将所有消息显示代码放入其中,并将您要显示的消息作为参数传递。

public void someMethod(String message, String anotherMessage){
          JOptionPane.showMessageDialog(null,message , anotherMessage, JOptionPane.INFORMATION_MESSAGE);
// some more code to run
}

编写完成后,您只需在 if 条件中调用此方法即可。

现在它看起来没什么用,但是如果你想在显示消息 id 后执行一些代码,那么你可以添加这个方法。

始终尝试尽可能简单地编写您的主要方法。只需尝试从中调用其他方法。

于 2013-06-15T17:29:04.740 回答
0

1. 级别和 2. 级别几乎相同。因此,将第一级提取到单独的方法将破坏下一级的代码。损坏的语法指导从第一级到第二级需要哪些信息。似乎只需要必要的数量。

按照这种重构方式也提示原来的 wrongB 和 questionnumB 没有正确使用。我冒昧地假设两轮都有单独的错误变量和问题变量。

这种方法的问题是,如果代码没有被很好地理解并且没有测试就很脆弱,它很可能会崩溃。但是,我发现它在较小的重构步骤不明显的情况下是有效的。

一般来说,所有方法都应该清晰易读。因为 main 方法是最顶级的方法,所以它应该清楚地说明程序中发生了什么。方法应该在同一抽象级别上并且非常短。

信息是使用 State-object 传递的,但在这种情况下,简单的数量可以从 runLevel 返回并作为参数传递给下一个。

我不知道对话框是否要清理,但我采取了一些措施来减少重复代码。整个事情可以抛光更多。我希望这可以给一些指导......

干净的代码(http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882)是一本非常好的关于重构和使方法和代码可读的书。

这是我的两分钱:

public class SummativeTwo {

public static void main(String[] args) throws IOException {
    BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
    {
        showYesNoCancelDialogWithFollowUp(
                "Welcome",
                "Welcome Million Dollar Madness! " + "Are you ready to play?",
                new DialogOption("Yes! I'm Excited!", new InformationDialog("Okie Dokie! Lets get started!", "Okie Dokie")),
                new DialogOption("Im kind of nervous..", new InformationDialog("Aw thats okay! Im sure you'll have fun!", "It's okay")),
                new DialogOption("Now Way! Ewww!", new InformationDialog("Well too bad so sad! You're going to have to play anyways!", "Too bad so sad")));

        showYesNoDialogWithFollowUp("INSTRUCTIONS?",
                "Would you like to know the instructions for this game?",
                new InformationDialog("There will be 3 levels in this game. As you go farther, the questions get harder and harder and each question \n. Each time you get a question right you will recieve a certain amount of money, which increases each time you pass each question. \n But be careful, because if you get 3 questions wrong in one level \n it's GAME OVER for you! Meaning you lose all your money. \n You may Cash Out at any point if you're not willing to risk losing the amount of money you have. Reach the end of \n the 3 levels and you take home all your money! \n GOOD LUCK!", "Instructions"),
                new InformationDialog("Your Choice", "Suit Yourself! Lets Start!"));


        showInformationMessage("Welcome to Level: 1 ", " level 1");

        State state = new State();
        runLevel1(state);
        showInformationMessage("LEVEL ONE COMPLETE!", "LEVEL 1");
        showInformationMessage("Cash on Hand: $ " + state.amount, "Cash");
        showInformationMessage("Welcome to Level: 2 ", " level 2");
        runLevel2(state);
        showInformationMessage("LEVEL TWO COMPLETE!", "LEVEL 2");
        JOptionPane.showMessageDialog(null, "Cash on Hand: $ " + state.amount, "Cash", JOptionPane.QUESTION_MESSAGE);

    }
}

static class State {

    int amount;
}

private static void runLevel1(State state) {
    int maxRuns = 6;
    int maxWrongs = 3;
    int increment = 150;
    runLevel(increment, maxRuns, maxWrongs, state);
}

private static void runLevel2(State state) {
    int maxRuns = 8;
    int maxWrongs = 3;
    int increment = 150;
    runLevel(increment, maxRuns, maxWrongs, state);
}

private static void runLevel(int increment, int maxRuns, int maxWrongs, State state) throws NumberFormatException, HeadlessException {
    int run = 1;
    int questionnum = 0;
    int wrong = 0;
    while (run <= maxRuns && wrong != maxWrongs) {
        run++;
        questionnum++;
        state.amount += increment;

        int numOne = additionOne();
        int numTwo = additionTwo();
        int answer = numOne + numTwo;

        String useranswerA = JOptionPane.showInputDialog(null, "Question #" + questionnum + " is for: $" + increment + "\n" + numOne + " + " + numTwo + " = ?", "Question", JOptionPane.INFORMATION_MESSAGE);
        int useranswer = Integer.parseInt(useranswerA);

        if (useranswer != answer) {
            wrong++;
            showInformationMessage("You got the wrong answer! \n The correct answer is: " + answer + " \n Questions Wrong: " + wrong, "Wrong Answer");
            askForCashOut(state.amount);
        } else if (useranswer == answer) {
            showInformationMessage("Correct!", "Right Answer");
            askForCashOut(state.amount);
        }
    }
}

public static int additionOne() {
    int x = (int) (Math.random() * 30);
    return x;
}

public static int additionTwo() {
    int x = (int) (Math.random() * 30);
    return x;
}

public static int numThree() {
    int x = (int) (Math.random() * 15);
    return x;
}

private static void askForCashOut(int amount) throws HeadlessException {
    if (askYesNo("Cash Out?", "CASH OUT with a total of $" + amount + "?")) {
        showInformationMessage("Thanks for Playing!", "Thank You!");
        System.exit(0);
    }
}

private static void showYesNoCancelDialogWithFollowUp(String title, String text, DialogOption yes, DialogOption no, DialogOption cancel) {
    DialogOption[] options = new DialogOption[]{yes, no, cancel};
    int n = JOptionPane.showOptionDialog(null, text, title, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
    options[n].dialog.show();
}

private static void showYesNoDialogWithFollowUp(String title, String text, InformationDialog afterYes, InformationDialog afterNo) {
    if (askYesNo(text, title)) {
        afterYes.show();
    } else {
        afterNo.show();
    }
}
private static final String[] YES_NO_OPTIONS = new String[]{"Yes Please", "Nope! I'm good!"};

private static boolean askYesNo(String text, String title) throws HeadlessException {
    int n = JOptionPane.showOptionDialog(null, text, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, YES_NO_OPTIONS, YES_NO_OPTIONS[0]);
    return n == JOptionPane.YES_OPTION;
}

private static void showInformationMessage(String text, String title) throws HeadlessException {
    JOptionPane.showMessageDialog(null, text, title, JOptionPane.INFORMATION_MESSAGE);
}

static class InformationDialog {

    private String text;
    private String title;

    public InformationDialog(String text, String title) {
        this.text = text;
        this.title = title;
    }

    public void show() {
        showInformationMessage(text, title);
    }
}

static class DialogOption {

    String text;
    InformationDialog dialog;

    public DialogOption(String text, InformationDialog dialog) {
        this.text = text;
        this.dialog = dialog;
    }

    @Override
    public String toString() {
        return text;
    }
}

}

于 2013-06-15T18:40:23.577 回答