【发布时间】:2019-06-19 19:59:08
【问题描述】:
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]);
}
}
}
【问题讨论】:
-
请将您的代码复制并粘贴到您的问题中。请不要链接到您的教科书的图像。这没有帮助。
-
@markspace 是的,我忘记添加我的代码,现在我添加了,非常感谢你提醒我:)
-
错误不是告诉你在哪一行你越界了吗?
-
我能看到的最简单的罪魁祸首是在分配
count变量时:int count = in.nextInt()。如果你读到一个小于 10 的 int,那么你接下来执行的 for 循环:for (int i =0; i<10; i++)将抛出异常。 -
嗯,还需要异常跟踪——你得到的异常的全文。它应该有行号。另外请用注释指出哪一行是实际错误,因为我们无法从您的代码中看到行号。
标签: java arrays sorting indexoutofboundsexception swap