保龄球实验室:if-else Ladder

时间:2015-04-09 00:24:41

标签: if-statement joptionpane

我想创建一个可以跟踪保龄球得分的实验室。输入值必须介于0-10之间。如果数字不同,我想显示“无效”。但是,在我的代码中,如果我连续出错,我的程序将不会检测到超出范围的数字为“无效”。我怎么编码才能让程序再次尝试,直到我输入一个可能的值?

import javax.swing.JOptionPane;
import java.io.*;
public class Driver14
{
   public static void main(String[] args)
   {
      int totalScore, frame, ball;
      totalScore = 0;
      frame = 1;
      ball = 1;
      JOptionPane.showMessageDialog(null,"Welcome to Computer Science Bowling!");
      while(frame<11){
         int score1 = Integer.parseInt(
                    JOptionPane.showInputDialog("Score " + totalScore + "\n" + "Frame " + frame + ", Ball " + ball));
         if(0<=score1 && score1<11){
            totalScore = totalScore + score1;
            ball++;
         }
         else{
            score1 = Integer.parseInt(
                    JOptionPane.showInputDialog("Invalid!\n" + "Score " + totalScore + "\n" + "Frame " + frame + ", Ball " + ball));
            totalScore = totalScore + score1;
            ball++;
         }
         int score2 = Integer.parseInt(
                    JOptionPane.showInputDialog("Score " + totalScore + "\n" + "Frame " + frame + ", Ball " + ball));
         if(0<=score2 && score2<11){
            totalScore = totalScore + score2;
            ball++;
         }
         else{
            score2 = Integer.parseInt(
                    JOptionPane.showInputDialog("Invalid!\n" + "Score " + totalScore + "\n" + "Frame " + frame + ", Ball " + ball));
            totalScore = totalScore + score2;
            ball++;
         }
         frame++;
         ball = 1;
      }
      JOptionPane.showMessageDialog(null,"Finished bowling!\nScore "+ totalScore);
   }
}

1 个答案:

答案 0 :(得分:0)

通常你可以使用这种模式:

public static String askUserForInpute(String message){
    String input = null;
    try {
        input = JOptionPane.showInputDialog(message);
        if(/*anyLogic*/) // OR any method that throws exception for instance Integer.parseInt(input)
            throw new Exception("YOUR MESSAGE");
    } catch (Exception e) {
        //ANY INFO YOU WANT
        output = askUserForInpute(message);
    }
    return input;
}

您要求用户输入,如果输入不正确,则显式或隐式(通过方法)抛出异常然后捕获它并再次调用相同的方法。这是可能性之一。