我试图执行以下操作:
Array
的方法,其中包含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 - "Assigned value never used"
编辑:如果你输入一个有效的整数,注释中的ingrid代码就能完美运行,但它不能捕获任何只会崩溃的异常
答案 0 :(得分:3)
你快到了。请尝试以下版本。
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();
}
}