package test5555;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class Test5555 {
private static int[] randomInteger;
public static void main(String[] args) {
boolean validInput = false;
randomInteger = new int[100];
Random rand = new Random();
for (int i = 0; i < randomInteger.length; i++)
randomInteger[i] = rand.nextInt();
int indexPosition = 0;
Scanner input = new Scanner(System.in); {
System.out.println("Please enter an integer for the array index position: ");
while(!validInput)
{
try
{
indexPosition = input.nextInt();
validInput = true;
System.out.println(randomInteger[indexPosition]);
} catch (InputMismatchException | IndexOutOfBoundsException ex) {
System.out.print("Please enter a valid integer between 0 and 100 or type quit to exit: ");
String s = input.next();
if(s.equals("quit")){
System.exit(0);
System.out.println(randomInteger[indexPosition]);
}
}
}
}
}
}
コードは完全に私は解決できない2つのマイナーしゃっくりを除いて動作します。あなたがそれを実行するとき
Please enter an integer for the array index position:
を取得します。bob
のような100以上の文字列を入力すると、Please enter a valid integer between 0 and 100 or type quit to exit:
が完璧です。しかし、quit
と入力するとPlease enter a valid integer between 0 and 100 or type quit to exit: BUILD SUCCESSFUL (total time: 2 minutes 2 seconds)
となり、終了しますが、不要な例外文が繰り返されます。あなたが正しい整数を入力した場合小さな問題 - ない正しい出力あなたは100を超える数を入力して
Please enter a valid integer between 0 and 100 or type quit to exit:
を受信するとプログラムがちょうどオフになり、それがBUILD SUCCESSFUL
の代わりに、配列
これは完璧に働いてくれてありがとう – archer