Please click here to see my task's screenshot
你好,你能帮我吗?我的代码有什么问题?我知道Array的长度或If语句有问题,但是我无法找出它。
非常感谢您!
import java.util.Scanner;
class TripleSwapping {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the count of your elements: ");
int count = in.nextInt();
System.out.println("Your array before sorting: ");
int A[] = new int [count];
for (int i = 0; i < 10; i++) {
A[i]=in.nextInt();
}
boolean changed =false;
do {
for (int i = 0; i < A.length-1; i++) {
if (!(A[i+1]>A[i]) && !(A[i+1] > A[i+2])) {
int temp;
temp = A[i];
A[i]= A[i+1];
A[i+1] =temp;
}
}
for (int i = 0; i < A.length-1; i++) {
if (A[i] >A[i+1]) {
int temp;
temp = A[i];
A[i]= A[i+1];
A[i+1] =temp;
changed=true;
}
}
}while(changed);
System.out.println("Your array after swapping");
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
}
}
答案 0 :(得分:0)
您将收到ArrayIndexOutOfBoundsException,因为如果输入的数字小于10,则会引发异常。
for (int i = 0; i < 10; i++) {
A[i]=in.nextInt();
}
代替
for (int i = 0; i < count; i++) {
A[i]=in.nextInt();
}