如何返回代码顶部?也许?

1 java int if-statement

我是编程Java的新手,并且我确信这是一个非常简单的解决方案.我有以下代码,它的工作原理,但我想知道如何更改它,所以如果用户输入的东西不是int,它会在它给出错误消息后循环回到顶部,所以它会要求一个温度又来了.提前致谢.

    Scanner in = new Scanner(System.in);
    //User input of temperature
    System.out.print("Enter temperature in Celsius: ");
    if (in.hasNextInt())
    {
        int temperature = in.nextInt();
        //Now determine what state the water will be in, either ice, gas, or water.
        if (temperature >=100)
        {
            System.out.print("Gas!");
        }
        else if ((temperature <100) && (temperature >0))
        {
            System.out.print("Water!");
        }
        else if (temperature <=0)
        {
            System.out.print("Ice!");
        }
    }
    else
    {
         System.out.println("Error: Not an Integer");
         System.out.print("Please enter temperature in Celsius: ");
    }
Run Code Online (Sandbox Code Playgroud)

sci*_*uff 5

把它移到一个方法中

public static void main( String args[] ){

    Scanner in = new Scanner(System.in);
    readInput( in );
}

public static void readInput( Scanner in ){

    System.out.print("Enter temperature in Celsius: "); 
    if ( in.hasNextInt() ){
        // do your stuff here
    }
    else {
        // print the errors
        readInput( in );
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在这里很好地使用递归 (2认同)