我正在介紹java。該程序應該能夠要求10個整數。然後它將整數標記爲字符串。然後我應該使用parseInt方法將字符串轉換爲Int。我也應該拋出一個try catch循環,所以如果有人輸入了除整數之外的任何東西,它會打印一個無效的語句。 try catch語句應該告訴用戶他們錯誤地輸入了哪個整數並要求他們重新輸入。如何使用此try catch方法?
繼承人的輸出應該是什麼樣子
歡迎彩擴10 - 例外。
輸入十個整數。
整數#1:50
整數#2:25
整數#3:37
整數#4:98
整數#5:77
整數#6:41
整數#7:44
整數#8:42
整數#9:29
整數#10位:Z
z是不是一個整數。請重新輸入整數#10:75您輸入50 25 37 98 77 41 44 42 29 75
整數的總輸入爲:518感謝您使用的例外程序。
這裏是我的代碼:
import java.util.Scanner;
import java.util.Arrays;
import java.util.List;
public class Exceptions10
{
public static void main(String[] args)
{
String string1, string2, string3, string4, string5, string6, string7, string8, string9, string10;
int Int1, Int2, Int3, Int4, Int5, Int6, Int7, Int8, Int9, Int10, Average;
Scanner scan = new Scanner(System.in);
System.out.print("Welcome to Minilab 10 -Exceptions");
System.out.print("\n\nEnter 10 Integers");
System.out.print("\n\nInteger 1: ");
string1 = scan.next();
System.out.print("Integer 2: ");
string2 = scan.next();
System.out.print("Integer 3: ");
string3 = scan.next();
System.out.print("Integer 4: ");
string4 = scan.next();
System.out.print("Integer 5: ");
string5 = scan.next();
System.out.print("Integer 6: ");
string6 = scan.next();
System.out.print("Integer 7: ");
string7 = scan.next();
System.out.print("Integer 8: ");
string8 = scan.next();
System.out.print("Integer 9: ");
string9 = scan.next();
System.out.print("Integer 10: ");
string10 = scan.next();
try
{
Int1 = Integer.parseInt(string1);
Int2 = Integer.parseInt(string2);
Int3 = Integer.parseInt(string3);
Int4 = Integer.parseInt(string4);
Int5 = Integer.parseInt(string5);
Int6 = Integer.parseInt(string6);
Int7 = Integer.parseInt(string7);
Int8 = Integer.parseInt(string8);
Int9 = Integer.parseInt(string9);
Int10 = Integer.parseInt(string10);
}
catch (NumberFormatException e)
{
System.out.println("Integer--- is not an integer. Please enter integer--- again: ");
}
int [] value = {Int1, Int2, Int3, Int4, Int5, Int6, Int7, Int8, Int9, Int10};
System.out.print("\nYou entered: ");
for (int i = 0; i < value.length; i++)
{
System.out.print(value[i]);
System.out.print(" ");
}
System.out.print("\n\n");
Average = (Int1 + Int2 + Int3 + Int4 + Int5 + Int6 + Int7 + Int8 + Int9 + Int10)/value.length;
System.out.print("The average of the integers is " + Average + "\n\n");
}
}
我的問題是我嘗試catch語句。我不知道在哪裏或如何放置它。
您當前的try/catch塊將處理任何不是數字的數字轉換。如果你想單獨捕捉每一個,並循環直到正確,你需要在每個'Integer.parseInt()'' – SnakeDoc
周圍放一個try/catch我強烈建議創建一個簡單的for循環並使用String數組來存儲字符串。它使你的代碼更加緊湊。 – Jyr