【问题标题】:How to limit the input integers from 1 to 9如何将输入整数限制为 1 到 9
【发布时间】:2014-11-07 08:06:16
【问题描述】:

我有一个用于点球大战的 Java 程序,我想将 b1、b2、b3 和 s1 限制为 1-9 之间的任何数字。如果输入不等于 1-9 再试一次。

 for (int i=0;i<=5;i++)

        {

            int b1, b2, b3, s1;
            int j=i+1;
            System.out.println("Enter the Numbers which you will block.... Please remember that it should be from 1-9 and nothingelse, 1 2 3 4 5 6 7 8 9");


            b1=Integer.parseInt(br.readLine()); // how to restrict this to numbers between 1 to 9
            b2=Integer.parseInt(br.readLine()); //this also
            b3=Integer.parseInt(br.readLine()); //this also

            System.out.flush();
            System.out.println("Enter The Number where you will score");
            s1=Integer.parseInt(br.readLine()); //this also

【问题讨论】:

    标签: input int limit


    【解决方案1】:
    while(b1 > 9 || b1 < 1) {
        System.out.println("Wrong number. Try again."); 
        b1=Integer.parseInt(br.readLine());
    }
    

    【讨论】:

      【解决方案2】:

      只需检查输入的内容。

      If (number >= 1 && number <= 9)
      {
       progressFurther();
      }
      else
      {
       enterAgain();
       checkAgain();
      }
      

      【讨论】:

        【解决方案3】:

        试试这种动态方式,

        public class testJava {
           public static void main(String[] args) {
               testJava j = new testJava();
               System.out.println(j.isBetween(1,1,9));
        
           }
            public boolean isNumeric(int value,int startValue,int endValue) {
                if(value >= startValue || value <= endValue)
                {
                    return true;
                }else{
                   return false;
                }
            }
        }
        

        【讨论】:

          【解决方案4】:

          只需使用一个简单的条件,例如:

          if (x >= 1 && x <= 9) {
              // handle the correct case
          } else {
              // handle the case where the input is not in the range 1-9
          }
          

          【讨论】:

            【解决方案5】:

            伪代码:

            if ((input > 9) || (input < 1)) {
                tryAgain()
            }
            

            我认为这就是您所需要的(不过,您必须检查每个变量)。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2013-05-27
              • 1970-01-01
              • 2020-11-14
              • 2020-08-24
              • 2013-08-11
              • 2017-10-18
              相关资源
              最近更新 更多