gpt4 book ai didi

java - 循环回到代码开头

转载 作者:行者123 更新时间:2023-12-02 04:08:44 27 4
gpt4 key购买 nike

我见过一些这样的线程,但我不完全理解如何将它实现到我的代码中。

import java.util.Scanner;

public class Test {



public static void main(String[] args)throws java.io.IOException {



Scanner reader = new Scanner(System.in);

System.out.println("Enter a number between 1-1000: ");

int n = reader.nextInt();

if(90<=n && n<=110) System.out.println(n + " is close to 100");
if(190<=n && n<=210) System.out.println(n + " is close to 200");
if(290<=n && n<=310) System.out.println(n + " is close to 300");
if(390<=n && n<=410) System.out.println(n + " is close to 400");
if(490<=n && n<=510) System.out.println(n + " is close to 500");
if(590<=n && n<=610) System.out.println(n + " is close to 600");
if(690<=n && n<=710) System.out.println(n + " is close to 700");
if(790<=n && n<=810) System.out.println(n + " is close to 800");
if(890<=n && n<=910) System.out.println(n + " is close to 900");
if(n>1000)System.out.println("Your number is too high");
else System.out.println("Your number is not close to any 100s");


}

}

如果整数超过 1000,我希望它能以某种方式循环回到用户输入部分。

最佳答案

您可以使用 while 循环,并且仅当输入的数字低于 1 或高于 1000 时才跳出循环

import java.util.Scanner;

public class Test {



public static void main(String[] args) throws java.io.IOException {


Scanner reader = new Scanner(System. in );
Boolean exit = false;

while (!exit) {
System.out.println("Enter a number between 1-1000: ");
int n = reader.nextInt();
if (n < 0 || n > 1000) {

System.out.println("That number was invalid");
} else {
exit = true;
if (90 <= n && n <= 110) System.out.println(n + " is close to 100");
if (190 <= n && n <= 210) System.out.println(n + " is close to 200");
if (290 <= n && n <= 310) System.out.println(n + " is close to 300");
if (390 <= n && n <= 410) System.out.println(n + " is close to 400");
if (490 <= n && n <= 510) System.out.println(n + " is close to 500");
if (590 <= n && n <= 610) System.out.println(n + " is close to 600");
if (690 <= n && n <= 710) System.out.println(n + " is close to 700");
if (790 <= n && n <= 810) System.out.println(n + " is close to 800");
if (890 <= n && n <= 910) System.out.println(n + " is close to 900");
}
}
}

}

关于java - 循环回到代码开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34006884/

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