gpt4 book ai didi

java - 努力解决 try/catch InputMismatch 异常并从数组中检索数据

转载 作者:行者123 更新时间:2023-12-01 21:42:29 25 4
gpt4 key购买 nike

我正在尝试执行以下操作:

  • 调用一个方法,该方法创建一个包含 100 个随机生成的整数的数组
  • 调用一个方法,提示用户输入数组的索引位置并返回输入的值。如果用户输入的值不是有效的整数,则抛出“输入不匹配异常”,提示用户问题并允许他们有机会输入正确的整数或退出程序。
<小时/>
package latest;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.Random;

public class Latest
{
private static int[] randomInteger;

public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int indexPosition = 0;
randomInteger = new int[100];
Random rand = new Random();
for (int i=0; i<randomInteger.length;i++)
randomInteger[i] = rand.nextInt();

while (indexPosition < 0 || indexPosition > 100)
{
try
{
// get array index position
System.out.println ("Hello, please enter an integer for the array index position: ");
indexPosition = input.nextInt();
}
catch (InputMismatchException e)
{
System.out.println ("You did not input a valid value. Please enter an Integer value between 0 and 100");
indexPosition = input.nextInt();
}
{
System.out.println ("You did not input a valid value. Please enter an Integer value between 0 and 100");
indexPosition = input.nextInt();
System.out.println (randomInteger[indexPosition]);
}
}
}
}

我的问题是代码编译但不输出任何内容,并且 IDE 提示 indexPosition -“分配的值从未使用”

编辑:如果您输入有效的整数,则注释中的 ingrid 代码可以完美运行,但它不会捕获任何异常,只会崩溃

最佳答案

你就快到了。尝试以下版本。

package latest;

import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.Random;

public class Latest {

private static int[] randomInteger;

public static void main(String[] args) {
int indexPosition = 0;
Scanner input = new Scanner(System.in);
randomInteger = new int[100];
Random rand = new Random();
for (int i = 0; i < randomInteger.length; i++)

randomInteger[i] = rand.nextInt();

System.out
.println("Hello, please enter an integer for the array index position: ");
do {
try {
// get array index position
indexPosition = input.nextInt();
} catch (InputMismatchException e) {
System.out
.println("You did not input a valid value. Please enter an Integer value between 0 and 100");
input.nextLine();
continue;
} catch (Exception e) {
System.out
.println("You did not input a valid value. Please enter an Integer value between 0 and 100");
input.nextLine();
continue;
}
if (indexPosition < 0 || indexPosition > 100) {
System.out
.println("You did not input a valid value. Please enter an Integer value between 0 and 100");
}

} while (indexPosition < 0 || indexPosition > 100);
System.out.println(randomInteger[indexPosition]);
input.close();
}
}

关于java - 努力解决 try/catch InputMismatch 异常并从数组中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36274654/

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