gpt4 book ai didi

java - java中循环出现问题

转载 作者:行者123 更新时间:2023-12-02 04:47:39 26 4
gpt4 key购买 nike

我试图让我的代码在用户完成其中一个选项后循环回到程序的开头。我似乎不知道如何让它正常工作。这是到目前为止我的代码

    static Scanner console = new Scanner(System.in);

public static void main(String[] args) {
// TODO Auto-generated method stub

int num1;
int num2;
int num3;

boolean opt1Done = false;
System.out.println("Select your next step");
System.out.println("1: Enter three numbers between 1 and 100.");
System.out.println("2: Order your number in ascending order");
System.out.println("3: Determine if the three inputs form a triangle");
System.out.println("4: Exit");

int answer = console.nextInt();
num1 = console.nextInt();
num2 = console.nextInt();
num3 = console.nextInt();

if (answer == 1) {
//do whatever for option 1
System.out.println("Enter a value for num1 between 1 and 100.");
System.out.println("Enter a value for num2 between 1 and 100.");
System.out.println("Enter a value for num3 between 1 and 100.");

opt1Done = true;
} else if (answer == 2) {
if (opt1Done) {
//...... do whatever to order the numbers
int[] arraynum;
arraynum = new int[3];

arraynum[0] = num1;
arraynum[1] = num2;
arraynum[2] = num3;

Arrays.sort(arraynum);

int i;

for (i=0; i < arraynum.length; i++) {
System.out.println("num:" + arraynum[i]);
}

} else {
System.out.println("you must complete Step 1 before Step 2");
}
} else if (answer == 3) {
if (opt1Done) {
//... do whatever to determine if triangle or not
if (num1+num2>num3 && num1+num3>num2 && num2+num3>num1)
{
System.out.print("TRIANGLE");
}
else
{
System.out.print("NO TRIANGLE");
}
} else {
System.out.println("you must complete Step 1 before Step 3");
}
}
}
}

基本上我需要它,以便在用户输入 2 并完成选项 2 后,程序将返回到开头并再次要求选择用户想要的选项。我怎样才能让它正常工作?另外,如果我没有看到代码有其他问题,请告诉我。谢谢

最佳答案

您需要的是将这整堆代码放入 while 循环中,该循环将始终为 true,并在最后再次询问用户输入。如果用户按 4(我认为是退出),只需在 while 循环中使用 Break 退出程序即可。

关于java - java中循环出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29528728/

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