2013-12-15 285 views
2

阅读了我书中我认为是相关的所有内容之后,我没有写任何帮助。我在Java中是一个完全新手,我必须解决以下问题: 我必须根据网球制作一个DialogProgram。该程序必须询问用户“谁得分”,并且用户必须输入“A”或“B”,并且必须执行直到A或B赢得比赛。 在我有的代码中把我的问题作为笔记。我希望他们会这样做最有意义。While&for循环和JOptionPane数据输入连接到for循环

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

首先,一些一般的Java的东西(我彻底明白了,你刚学):

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

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

循环结束后,我会检查是否a == desiredScore并相应地打印一条消息。然后检查是否b == desiredScore并打印一条消息。

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. 
    } 
    } 
}