gpt4 book ai didi

java - 如何循环这个简单的程序?

转载 作者:行者123 更新时间:2023-11-29 05:01:21 24 4
gpt4 key购买 nike

我如何循环整个程序?

public class Experiments {
public static void main(String[] args) {
int n;

System.out.print("Please enter a number:");
n = TextIO.getlnInt();

while (n<3) {
System.out.print("Please enter another number:");
n = TextIO.getlnInt();
}
while (n<=5) {
System.out.println("Number entered should be more than 5.");
System.out.println("Please re-enter:");
n=TextIO.getlnInt();
}
if (n%2==0) {
n=n*2+1;
}
else {
n=n*2;
}
System.out.println("The result is "+n +".");
}
}

当它打印出结果时:

The result is 14.

我想让它说这样的话:

Had fun? Lets do it again.
Please enter a number:

Had fun? Want do it again. Press y/n.
Please enter a number:

最佳答案

你必须做这样的事情:

Scanner s = new Scanner(System.in);
char c;
do {
your_code
c = s.next().charAt(0);
} while(c == 'y');

多亏了这个,你的程序每次都会询问你是否要继续,当你输入“y”时,它会再次循环。否则它将退出循环。

关于java - 如何循环这个简单的程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32003435/

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