【问题标题】:this program after i enter invalid inputs ,, i need to start again from first ,, how can i do it in java?这个程序在我输入无效输入后,我需要从头开始,我怎么能在java中做到这一点?
【发布时间】:2021-07-09 03:36:54
【问题描述】:
System.out.println(" Enter the three sides of Triangle ");
       Scanner s = new Scanner (System.in);
       
       System.out.print(" a = "  ); 
       double a = s.nextDouble();
       
       System.out.print(" b = "  ); 
       double b = s.nextDouble();

       System.out.print(" c = "  ); 
       double c = s.nextDouble();

       if ( a+b>c && b+c>a && c+a>b && a!=0  && b!=0  && c!=0    )
       {
           
           System.out.println("The perimeter of a Triangle = " + (a+b+c));
           
       } 
       else {
           
       System.out.println(" invalid inputs  ");                                

       }

【问题讨论】:

    标签: java


    【解决方案1】:

    您可以创建一个while 循环,该循环在用户输入有效数字时中断,并继续输入直到用户继续输入无效输入,如下所示:

            System.out.println(" Enter the three sides of Triangle ");
            Scanner s = new Scanner(System.in);
    
            while (true) {
                System.out.print(" a = ");
                double a = s.nextDouble();
    
                System.out.print(" b = ");
                double b = s.nextDouble();
    
                System.out.print(" c = ");
                double c = s.nextDouble();
    
                if (a + b > c && b + c > a && c + a > b && a != 0 && b != 0 && c != 0) {
                    System.out.println("The perimeter of a Triangle = " + (a + b + c));
                    break; // Break on valid input
                } else {
                    System.out.println(" invalid inputs  ");
                }
            }
    

    【讨论】:

    【解决方案2】:

    由于 java 是 OOP 语言,我总是喜欢朝那个方向思考,它可以为您的问题提供以下解决方案:

    class Triangle {
      double a, b, c;
      public void enterSides(Triangle t){
        //Get inputs from user into t.a, t.b and t.c
      }
    
      public bool checkSides(Triangle t){
        //if triangle condition is valid, return true else false
      }
    }
    
    class Solution{
      public static void main(String args[])
      {
        Triangle t=new Triangle();
        t.enterSides();
        if(t.checkSides()) {
          //print parimeter
        }
        else{
          t.enterSides();
        }
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      • 2014-06-07
      • 1970-01-01
      • 2020-12-19
      相关资源
      最近更新 更多