所以基本上我一直試圖讓這個簡單的小代碼作業,但我遇到了回圈的問題。我想要發生的基本上是這樣的:用戶輸入一個整數,如果它不是一個整數,它將顯示一個錯誤并要求一個整數,直到給出整數。我很難設定回圈,因為我不知道該怎么做。我很新而且很笨,所以這可能真的很容易,但我有點白癡而且很爛,但我正在學習。
這就是我所擁有的。
import java.util.Scanner;
public class Loop{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " Index);
}
else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
}
else {
System.out.println("Error: Index is not Integer.");
}
}
}
uj5u.com熱心網友回復:
您可以while為此使用回圈。
while (true) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " Index);
break;
} else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
} else {
System.out.println("Error: Index is not Integer.");
}
}
uj5u.com熱心網友回復:
您需要對代碼使用回圈(for 或 while)。你可以這樣做。
import java.util.Scanner;
public class Loop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " Index);
} else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
} else {
System.out.println("Error: Index is not Integer.");
}
// add same condition to break the loop
}
// close the scanner
scan.close()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/351537.html
