前提・実現したいこと
javaを学習していて任意に与えられた数列を降順にソートする機能を実装したいです
発生している問題・エラーメッセージ
ソートに関するif文のところにエラーが出てしまいます。
エラーメッセージ
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
該当のソースコード
javaここに言語名を入力
ソースコード
package kadai0930;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Kadai2_3 {
public static void main(String args[])throws IOException{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("データ数=");
int n = Integer.parseInt(buf.readLine());
int[] res1 = new int[n];
for(int i = 0;i < n;i++) {
buf = new BufferedReader(new InputStreamReader(System.in));
res1[i] = Integer.parseInt(buf.readLine());
}
int[] res2 = res1;
for(int i = 0;i < n - 1;i++) {
for(int j = 0;j < n;j++) {
int a = 0;
//この下のif文の行がエラー箇所とされています
if(res1[n - (j + 1)]>res1[n - (j + 2)]) {
a = res1[n - (j + 2)];
res1[n - (j + 2)] = res1[n - (j + 1)];
res1[n - (j + 1)] = a;
}else {
break;
}
}
}
System.out.print("入力データ=");
for(int i = 0;i < n;i++) {
System.out.print((i+1) + ";" + res2[i] + " ");
}
System.out.print("\n");
System.out.print("ソート結果=");
for(int i = 0;i < n;i++) {
System.out.print((i+1) + ";" + res1[i] + " ");
}
}
}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/10/02 09:18