配列の添え字を変えずに再入力する方法がわからない。
String型で入力された際に例外処理でint型で入力してくださいとエラーを出すのですが、その際に配列の添え字を変えずにそのまま再入力していく方法がわかりません。
下記の例のようにNums[2]を変えずに再入力をしたい
例: Index --> 2
Nums[2] --> a
Input Mismatch
Nums[2] --> b
Input Mismatch
Nums[2] --> c
Input Mismatch
before
1import java.util.InputMismatchException; 2import java.util.Scanner; 3public class Kadai1104 { 4 5 public static void main(String[] args) { 6 Scanner sc = new Scanner(System.in); 7 8 int[] nums = {-1,-1,-1,-1,-1}; 9 10 int index = 0; 11 do { 12 try { 13 System.out.print("Index --> "); 14 index = sc.nextInt(); 15 System.out.print("Nums[" + index + "] --> "); 16 nums[index] = sc.nextInt(); 17 }catch(ArrayIndexOutOfBoundsException e) { 18 System.out.println("Index Error!"); 19 System.out.println(); 20 }catch(InputMismatchException e){ 21 System.out.println("Input Mismatch"); 22 sc.next(); 23 System.out.println(); 24 } 25 }while(index != -1); 26 System.out.println(); 27 for(int i=0; i<nums.length; i++) { 28 System.out.println("Nums[" + i + "] : " + nums[i]); 29 } 30 } 31} 32```after 33
import java.util.InputMismatchException;
import java.util.Scanner;
public class Kadai1104 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] nums = {-1,-1,-1,-1,-1};
int index = 0;
do {
try {
System.out.print("Index --> ");
index = sc.nextInt();
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Index Error!");
System.out.println();
}
}while(index != -1);
do {
try {
System.out.print("Nums[" + index + "] --> ");
nums[index] = sc.nextInt();
}catch(InputMismatchException e){
System.out.println("Input Mismatch");
sc.next();
System.out.println();
}
}while(index != -1);
System.out.println(); for(int i=0; i<nums.length; i++) { System.out.println("Nums[" + i + "] : " + nums[i]); } }
}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/07/05 03:29
2019/07/05 03:46
2019/07/05 05:25
2019/07/05 05:26
2019/07/05 11:11