在阅读了我认为与之相关的所有书籍后,没有任何内容对我在这里的写作有所帮助。我是Java的完全新手,我必须解决以下问题:
我必须根据网球制作一个DialogProgram。该程序必须询问用户“谁知道了点”,用户必须键入“ A”或“ B”,并且必须执行该操作,直到游戏被A或B获胜为止。
在代码中,我已将我的问题作为注释。我希望这样他们将最有意义。

import java.awt.Color;
import acm.program.*;
import acm.graphics.*;
import javax.swing.JOptionPane;

public class A3 extends DialogProgram
{
  public void run ()
  {
    JOptionPane.showMessageDialog(null, "Playing: Who got the point?");

    int A = 0;
    int B = 0;
    int C = 0;

    /*
     * How do I make a loop to execute the JOptionPane until the if or else statement
     * in the for loop is achieved?
     * I think it should be with a while loop but how do I tell it to ask for input
     * until the for loop is achieved?
     */
    while ()
    {
      /*
       * I need the JOptionPane to take in only A or B as an answer each time it pops out.
       * How do I tell the JOptionPane to do that?
       * How to connect the input of A or B in the JOptionPane to the for loop so that it
       * counts the times A is inputed and the times B is inputed
       */
      String input = JOptionPane.showInputDialog("Enter A or B");

      for (C = 0; A >= 4 && B <= A-2; B++)
      {
        if (A >= 4 && B <= A-2)
        {
          // In this case A wins
          JOptionPane.showMessageDialog(null,"Player A Wins!");
        }
        else if (B >= 4 && A <= B-2)
        {
          // In this case B wins
          JOptionPane.showMessageDialog(null,"Player B wins!");
        }
      }
    }
  }
}

最佳答案

首先,介绍一些Java常规知识(我完全理解您只是在学习):


“注释”称为“注释”
变量(例如A,B和C)应以小写字母(例如a,b和c)开头。


至于您的问题,我不太了解int C在做什么。对于您的while循环,我将添加两个条件。检查是否a == desiredScore并检查b == desiredScoredesiredScore可能应该是它自己的变量,当前看起来像4。获得输入(存储在input字符串中)后,您应该对其进行一些检查。 String有很多成员函数,您会发现它们非常有用。特别要检查.equalsIgnoreCase。如果输入的内容与您想要的不匹配,请打印一条信息,并不要更新任何变量(循环将继续进行)。

循环退出后,我将检查a == desiredScore并相应地打印一条消息。然后检查b == desiredScore并打印一条消息。

08-18 23:24