我不是 Java 新手,但我在 JUnit 中。我在使用簡單的 for 回圈時遇到問題。我正在使用冒泡排序對陣列元素進行排序,但我不知道為什么最后兩個元素在回圈期間消失了。我知道這將是一件小事,但我找不到錯誤。請問你能幫幫我嗎?這是我的課:
package exercise5;
public class Ejercicio5 {
public static int[] sort(int[] arrayNums) {
// array that I have tried: {6,5,8,3,7,1}; [6]
System.out.println("size: " arrayNums.length);
for (int j = 0; j < arrayNums.length; j ) {
System.out.println("j:" j);
if (arrayNums[j] > arrayNums[j 1]) {
System.out.println("entra");
int numGuardado = arrayNums[j 1];
arrayNums[j 1] = arrayNums[j];
arrayNums[j] = numGuardado;
}
print(arrayNums);
}
return arrayNums;
}
public static void print(int[] arrayParaImprimir) {
System.out.println("Array:");
for (int j = 0; j < arrayParaImprimir.length; j ) {
if (j != arrayParaImprimir.length - 1) {
System.out.print(arrayParaImprimir[j] ", ");
} else {
System.out.print(arrayParaImprimir[j] "\n");
}
}
}
}
我的 JUnit5 測驗類:
package exercise5;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import junit.framework.TestCase;
public class Ejercicio5Test extends TestCase{
@Test
public void resultadoCorrecto(){
int[] correct = {1,3,5,6,7,8};
int[] array = {6,5,8,3,7,1};
int[] result = Ejercicio5.sort(array);
Assert.assertArrayEquals(result, correct);
}
@Test
public void resultadoIncorrecto(){
int[] correct = {1,3,5,6};
int[] array = {3,5,6,1};
int[] result = Ejercicio5.sort(array);
Assert.assertArrayEquals(result, correct);
}
}
當 j 等于 4 時,排序是:5, 6, 3, 7, 1, 8 但是當 j 傳遞到 5 時,兩個元素消失。此外,在我的 Test 類中只有兩種方法,但是,當我運行它時,它又識??別出一個并給我一個錯誤:

這是我嘗試過的陣列 {1,3,5,6,7,8} 這是我期望的 {5,6,3,7,1,8} 陣列大小為 6,而不是元素消失。
uj5u.com熱心網友回復:
for (int j = 0; j < arrayNums.length; j ) {
這會為輸入中的每個數字回圈。然后你..
if (arrayNums[j] > arrayNums[j 1]) {
將此與輸入中的下一個數字進行比較。因此,在最后一個回圈中,您將最后一個數字 ( arrayNums[j]) 與之后的數字進行比較。不存在,因此,ArrayIndexOutOfBoundsEx。
你想少回圈一個。
uj5u.com熱心網友回復:
你錯過了一個回圈這里是正確的代碼 -
public class Ejercicio5 {
//you don't need to return as it modifies exiting array
public static void sort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n - 1; i )
for (int j = 0; j < n - i - 1; j )
if (arr[j] > arr[j 1]) {
// swap arr[j 1] and arr[j]
int temp = arr[j];
arr[j] = arr[j 1];
arr[j 1] = temp;
}
}
/* Prints the array */
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; i)
System.out.print(arr[i] " ");
System.out.println();
}
public static void main(String args[])
{
int[] array = {6,5,8,3,7,1};
Ejercicio5.sort(array);
System.out.println("Sorted array");
Ejercicio5.printArray(array);
}
}
輸出 -Sorted array 1 3 5 6 7 8
并且您的測驗用例現在應該可以進行微小的更改
uj5u.com熱心網友回復:
只需將其用于 int 陣列:
Arrays.sort(arr);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/533206.html
標籤:爪哇数组
上一篇:如何用ajax計算總結果?
