在java中使用方法

在java中使用方法,java,oop,Java,Oop,我们应该在程序中使用方法,但我在将它们合并到程序中时遇到了困难。我的程序就像一个数学游戏,问简单的加法和加减法问题。我希望所有的计算都是方法,但我很难返回一个完整的方程 我需要一些帮助,当我需要去的方向,以便有效地使用我的程序中的方法,我应该在哪里做我的计算!以及它自己的方法应该是什么,主要的方法应该是什么 import javax.swing.*; import java.io.*; public class SummativeTwo { public static void mai

我们应该在程序中使用方法,但我在将它们合并到程序中时遇到了困难。我的程序就像一个数学游戏,问简单的加法和加减法问题。我希望所有的计算都是方法,但我很难返回一个完整的方程

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

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;
  }
}
import javax.swing.*;
导入java.io.*;
公共课总结{
公共静态void main(字符串[]args)引发IOException{
BufferedReader myInput=新的BufferedReader(新的InputStreamReader(System.in)){
Object[]options={“是的!我很兴奋!”,“我有点紧张…”,“现在走吧!EWW!”;
int n=JOptionPane.showOptionDialog(null,“欢迎百万美元疯狂!”+“准备好玩了吗?”,“欢迎”,JOptionPane.YES\u NO\u CANCEL\u选项,JOptionPane.QUESTION\u消息,null,选项,选项[2]);
if(n==JOptionPane.YES\u选项){
showMessageDialog(null,“好的,让我们开始吧!”,“好的,好的”,JOptionPane.INFORMATION\u MESSAGE);
}
if(n==JOptionPane.NO_选项){
showMessageDialog(null,“哦,没关系!我相信你会玩得很开心!”,“没关系”,JOptionPane.INFORMATION\u MESSAGE);
}
if(n==JOptionPane.CANCEL_选项){
showMessageDialog(null,“太糟糕了,太悲伤了!你无论如何都得玩!”,“太糟糕了,太悲伤了”,JOptionPane.INFORMATION\u MESSAGE);
}
Object[]optionsA={“是的,请”,“不!我很好!”;
int x=JOptionPane.showOptionDialog(null,“您想知道这个游戏的说明吗?”,“说明?”,JOptionPane.YES\u NO\u选项,JOptionPane.QUESTION\u消息,null,optionsA,optionsA[0]);
if(x==JOptionPane.YES\u选项){
JOptionPane.showMessageDialog(null,"此游戏将分为3个级别。随着你越走越远,问题会越来越难,每个问题都会越来越难。\n每次你答对一个问题,你就会收到一定数量的钱,每次你通过每个问题,钱都会增加。\n但是要小心,因为如果你在一个级别中答错了3个问题,\n你的游戏就结束了!意思是哟你失去了所有的钱。\n如果你不愿意冒失去你所拥有的钱的风险,你可以在任何时候兑现。达到\n 3个级别的末尾,你就把所有的钱都带回家!\n祝你好运!,“说明”,JOptionPane.INFORMATION\u MESSAGE);
}
if(x==JOptionPane.NO_选项){
showMessageDialog(null,“适合自己!让我们开始!”,“您的选择”,JOptionPane.INFORMATION\u MESSAGE);
}
showMessageDialog(null,“欢迎来到级别:1”,“级别1”,JOptionPane.INFORMATION_消息);
//一级
int错误=0;
int run=1;
int questionnum=0;
整数金额=0;

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

您有三个非常相似的函数:
additionOne
additionTwo
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;

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

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

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

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

public void someMethod(String message, String anotherMessage){
          JOptionPane.showMessageDialog(null,message , anotherMessage, JOptionPane.INFORMATION_MESSAGE);
// some more code to run
}
编写之后,只需在if条件中调用此方法

现在它看起来没有多大用处,但如果您希望在显示消息id之后执行一些代码,那么您可以添加这个方法


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

首先,取出任何重复的方法。 因此,对于两组块:

if (useranswer != answer)

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

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

删除较小的块后,您可能会发现有新的“小”块
else if (useranswer == answer)
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;
    }
}