英文:
Why does my code not move on from taking the specified number of inputs?
问题
我附上的代码片段是一个未经优化的冒泡排序方法。我遇到的问题是程序一直在接受输入,而不继续执行主方法中的函数调用。是否有人能指导我如何从代码中删除这个异常?
以下是我的代码:
import java.util.*;
public class Main {
public static void bubbleSort(int[] arr){
int i,j,t,n;
n=arr.length;
for (i=0;i<(n-1);++i){
for (j=1;j<(n-i-1);++j){
if(arr[i]>arr[i+1]){
t=arr[i];
arr[i]=arr[i+1];
arr[i+1]=t;
}
}
}
printSortedArray(arr);
}
public static void printSortedArray(int[] arr){
System.out.print("{");
for (int j : arr) System.out.print(j + ",");
System.out.print("}");
}
public static void main(String[] args) {
int n;
Scanner a = new Scanner(System.in);
System.out.println("Enter a range for array");
n=a.nextInt();
int [] b=new int[n];
for (int i=0;i<n;++i)
b[i]=a.nextInt();
bubbleSort(b);
}
}
英文:
The code fragment I have attached is of a non-optimized method for bubble sorting.The problem I am facing is that the program keeps on taking inputs and doesn't go on to the function call in the main method.Would someone guide me as to what i should do to remove this anomaly from my code?
>Here is my Code:-
import java.util.*;
public class Main {
public static void bubbleSort(int[] arr){
int i,j,t,n;
n=arr.length;
for (i=0;i<(n-1);++i){
for (j=1;j<(n-i-1);++j){
if(arr[i]>arr[i=1]){
t=arr[i];
arr[i]=arr[i+1];
arr[i+1]=t;
}
}
}
printSortedArray(arr);
}
public static void printSortedArray(int[] arr){
System.out.print("{");
for (int j : arr) System.out.print(j + ",");
System.out.print("}");
}
public static void main(String[] args) {
int n;
Scanner a = new Scanner(System.in);
System.out.println("Enter a range for array");
n=a.nextInt();
int [] b=new int[n];
for (int i=0;i<n;++i)
b[i]=a.nextInt();
bubbleSort(b);
}
}
答案1
得分: 2
这里有一个拼写错误在这个 if (method bubbleSort) 导致了一个无限循环。
更改:
if (arr[i] > arr[i=1]) {
为:
if (arr[i] > arr[i+1]) {
英文:
There is a typo in this if (method bubbleSort) which causes an infinite loop.
Change:
if(arr[i]>arr[i=1]){
To:
if(arr[i]>arr[i+1]){
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论