while & for 循环和 JOptionPane 数据输入连接到 for 循环



在阅读了我书中所有我认为相关的内容后,我在这里写作。我是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字符串中)后,您应该对其进行几次检查。字符串有一组成员函数,您会发现这些函数非常有用。特别是检查.equalsIgnoreCase。如果输入与您想要的不匹配,请打印一条消息,说明不匹配,并且不要更新任何变量(循环将继续)。

循环退出后,我会检查a == desiredScore是否存在,并相应地打印一条消息。然后检查是否为b == desiredScore,并相应打印消息。

基本上是supersam654所说的,并添加了一些内容。实际上,您必须增加整数变量,当用户选择任意一个播放器时,Java不会神奇地为您保留分数。此外,你的for循环毫无意义,因为在其中B总是得到一分。

这里有一个例子:

public void run(int minimumScoreToWin) {
  int a = 0;
  int b = 0;
  JOptionPane.showMessageDialog(null, "Playing a set of tennis.");
  while (true) { // This loop never ends on its own.
    JOptionPane.showMessageDialog(null, "Score is A: " + a + ", B: " + b +
                                        ". Who got the next point?");
    String input = JOptionPane.showInputDialog("Enter A or B");
    if (input.equalsIgnoreCase("A") {
      a++;
    } else if (input.equalsIgnoreCase("B") {
      b++;
    } else {
      JOptionPane.showMessageDialog(null, "Cannot compute, answer A or B.");
      continue; // Skip to next iteration of loop.
    }
    if (a >= minimumScoreToWin && b <= a-2) {
      JOptionPane.showMessageDialog(null,"Player A Wins!");
      break; // End loop.
    } else if (b >= minimumScoreToWin && a <= b-2) {
      JOptionPane.showMessageDialog(null,"Player B Wins!");
      break; // End loop.
    }
  }
}

最新更新