[英]Having trouble with loop in java
我試圖讓我的代碼在用戶完成選項之一后循環回到程序的開頭。 我似乎無法弄清楚如何使其正常工作。 到目前為止,這是我的代碼
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循環中,這將始終是正確的,最后要求用戶再次輸入。 如果用戶按4(我認為是退出),只需在while循環中使用break退出程序。
int input;
do {
//---
//The rest of your logic
//---
} while(input != 4);
您可以嘗試這樣。
Boolean p = true;
while(p){
System.out.println(
" Select an option:\n" +
"1: Enter three numbers between 1 and 100.\n" +
"2: Order your number in ascending order\n"+
"3: Determine if the three inputs form a triangle\n"+
"4: Exit\n"
);
switch(){
case 1:
.
.
.
case 4:
System.exit();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.