ユーザーにN個入力された文字列を逆順で表示するクラスを作成しています。ユーザーに入力されたNの値に応じて配列を作成し、それをfor文で表示しようと試みているのですがうまくいきません。
java
1import java.io.*; 2 3public class RecentEvent{ 4 public static void main(String[] args)throws IOException{ 5 6 System.out.print("繰り返す数: "); 7 8 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 9 String str = br.readLine(); 10 int str2 = Integer.parseInt(str); 11 12 String[] test = new String[str2 -1]; 13 14 for(int i = 0; i < str2; i++){ 15 16 String abc; 17 abc = br.readLine(); 18 test[i] = abc; 19 20 } 21 System.out.println("--- 近況の報告 ---"); 22 for(int j = str2 -1; j < str2; j--){ 23 System.out.println(test[j]); 24 } 25 26 } 27}
該当の部分はException in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
at RecentEvent.main(RecentEvent.java:18)です。
回答1件
あなたの回答
tips
プレビュー