[英]How can i display an error message in Java
我是初學者,我必須編寫一個代碼,根據用戶給我的半徑計算面積和周長。 這部分很簡單,但老師還希望我只接受有效的整數,並讓用戶在輸入不正確時重新輸入一個值......
所以我能夠讓它顯示每種情況的錯誤消息,除非他們輸入負整數:
import java.util.Scanner;
public class GetCircle
{
public static void main(String []args)
{
Scanner input = new Scanner(System.in);
int radius;
do {
System.out.print("Please enter size of radius (Must be integer): ");
while (!input.hasNextInt()) {
System.out.print("That is not a valid number, please try again :");
input.next();
}
radius = input.nextInt();
} while (radius < 0);
System.out.println("The radius is: " + radius);
}
}
所以這就是我得到的結果:
請輸入半徑大小(必須是整數):aaa
該號碼無效,請重試:4.5555
這不是一個有效的數字,請重試:-5
請輸入半徑大小(必須是整數):-5
請輸入半徑大小(必須是整數):-8.777
這不是一個有效的數字,請再試一次:-4
請輸入半徑大小(必須是整數):
** 所以只要它是一個負整數,它就不會顯示錯誤消息......
我該如何解決這個問題?
有很多方法可以做到,但對於初學者來說,最簡單的方法是在給radius
賦值和外部 while 循環結束之間添加if
語句:
if (radius < 0) {
System.out.print("The radius must not be negative, please try again :");
}
如果我的問題是正確的,那么您就不需要使用!input.hasNextInt()
。 這就是你如何做到的。
import java.util.Scanner;
public class GetCircle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int radius = 0;
System.out.print("Please enter size of radius (Must be integer): ");
while (true){
if(input.hasNextInt()){
radius = input.nextInt();
if (radius < 0){
System.out.println("That is not a valid number, please try again :");
System.out.println("Please enter size of radius (Must be integer): ");
} else {
System.out.println("The radius is: " + radius);
}
} else {
System.out.println("That is not a valid number, please try again :");
System.out.println("Please enter size of radius (Must be integer): ");
input.next();
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.