gpt4 book ai didi

Java 输入不匹配异常?

转载 作者:太空宇宙 更新时间:2023-11-04 06:21:19 26 4
gpt4 key购买 nike

如果用户输入字符串而不是整数,我会尝试对我的代码执行异常。我的代码会将最大索引的位置交换到最小索引。你能和我一起尝试纠正这个问题吗?

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 block 中,您将 InputMismatchException 对象命名为 h.这也是您的循环计数变量。改变这一点。

catch(InputMismatchException ex)
{
System.out.println("Please re-enter 10 numbers as an exception "
+ ex.toString());
continue;
}

此外,您的第二个问题是 catch block 中的 print 语句被自动视为下一个循环的扫描仪输入。因此,一旦输入错误字符串,程序就不允许输入更多数字。您需要做的是首先使用 data.next() 来使用您的错误消息。

catch (InputMismatchException ex) {
System.out.print("Please re-enter 10 numbers as an exception "
+ ex.toString());
data.next();

}

关于Java 输入不匹配异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27392432/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com