gpt4 book ai didi

java - 如何返回代码顶部?或许?

转载 作者:行者123 更新时间:2023-11-29 07:16:08 25 4
gpt4 key购买 nike

我是 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: ");
}

最佳答案

把它移到一个方法中

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 );
}
}

关于java - 如何返回代码顶部?或许?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9449169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com