[英]Java InputMismatchException?
如果用戶輸入字符串而不是整數,我會嘗試對代碼進行異常處理。 我的代碼會將最大索引的位置交換為最小索引。 你能和我一起糾正這個問題嗎?
import java.util.Scanner;
import java.util.InputMismatchException;
public class ArraySwap
{
static int h;
static Scanner data = new Scanner(System.in);
static int[] list = new int[10];
public static void main(String[] args)throws InputMismatchException
{
System.out.println("Please enter 10 numbers: ");
for(h = 0; h < list.length; h++)
{
try
{
list[h] = data.nextInt();
}
catch(InputMismatchException h)
{
System.out.println("Please re-enter 10 numbers as an exception "
+ h.toString());
continue;
}
}
swap();
}
public static void printArray(int[] list)
{
int counter;
for(counter = 0; counter < list.length; counter++)
System.out.print(list[counter] + " ");
}
public static int smallestIndex(int[] list)
{
int length1 = list.length;
int counter;
int minIndex = 0;
for (counter = 1; counter < length1; counter++)
if (list[minIndex] > list[counter])
minIndex = counter;
return minIndex;
}
public static int largestIndex(int[] list)
{
int length2 = list.length;
int counter;
int maxIndex = 0;
for (counter = 1; counter < length2; counter++)
if (list[maxIndex] < list[counter])
maxIndex = counter;
return maxIndex;
}
public static void swap()
{
System.out.print("List of elements: ");
printArray(list);
System.out.println();
int min_index = smallestIndex(list);
int max_index = largestIndex(list);
int min_num = list[min_index];
System.out.println("Largest element in list is: "
+ list[max_index]);
System.out.println("Smallest element in list is: "
+ list[min_index]);
min_num = list[min_index];
list[min_index] = list[max_index];
list[max_index] = min_num;
System.out.print("Revised list of elements: ");
printArray(list);
System.out.println();
}
}
您已經在整數輸入上進行異常處理:
try
{
list[h] = data.nextInt();
}
catch(InputMismatchException h)
{
System.out.println("Please re-enter 10 numbers as an exception "
+ h.toString());
continue;
}
}
您的問題是,在catch塊中,您將InputMismatchException對象命名為h。 這也是您的循環計數變量。 改變它。
catch(InputMismatchException ex)
{
System.out.println("Please re-enter 10 numbers as an exception "
+ ex.toString());
continue;
}
另外,您的第二個問題是catch塊中的print語句將自動作為下一個循環的Scanner輸入。 因此,一旦輸入錯誤字符串,該程序將不允許再輸入任何數字。 您需要做的是首先使用data.next()消耗您的錯誤消息。
catch (InputMismatchException ex) {
System.out.print("Please re-enter 10 numbers as an exception "
+ ex.toString());
data.next();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.