在阅读了我认为相关的所有内容之后,我没有帮助我写这里。我是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!");
}
}
}
}
}
答案 0 :(得分:0)
首先,一些普通的Java事物(我完全理解你只是在学习):
至于你的问题,我并不完全理解int C
正在做什么。对于while
循环,我会在其中加入两个条件。检查是否a == desiredScore
并检查是否b == desiredScore
。 desiredScore
应该是它自己的变量,目前看起来像4。获得输入(存储在input
字符串中)后,您应该对其进行一些检查。 String有许多成员函数,你会发现它们非常有用。特别看看.equalsIgnoreCase。如果输入与您想要的不匹配,请打印一条说明的消息,不要更新任何变量(循环将继续)。
循环退出后,我会检查是否a == desiredScore
并相应地打印一条消息。然后检查是否b == desiredScore
并打印一条消息。
答案 1 :(得分:0)
基本上是什么 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.
}
}
}