嗨,我是编程新手,今天我正在编写一个Java数组任务的代码,并且在开始时我试图测试我已经完成了什么,并且在第一个for循环(数组读取)程序不停止读一个数字,即使我已经输入一个数字(n)的长度。请帮忙 ?因为一旦执行for循环if条件里面,然后changed
设置为true
和它的价值从未改变为假导致无限循环由while循环做Java数组读取循环永不结束?
import java.util.Scanner;
public class ReadTwoElementsForArrayAndSum {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("Please enter N element:");
int n = in.nextInt();
System.out.print("Please enter K element, for k < N: ");
int k = in.nextInt();
int[] arrayN = new int[n];
System.out.print("Please enter N numbers for the array: ");
for(int i = 0; i < arrayN.length; i++) {
arrayN[i] = in.nextInt();
}
boolean changed = false;
do {
int temp = 0;
for(int i = 0; i < (arrayN.length-1); i++) {
if(arrayN[i] > arrayN[i+1]){
temp = arrayN[i];
arrayN[i] = arrayN[i+1];
arrayN[i+1] = temp;
changed = true;
}
}
} while (changed);
for(int i = 0; i < arrayN.length; i ++) {
System.out.printf("%d", arrayN[i]);
System.out.print(k);
}
in.close();
}
}
是的的确控制不断进入这一行正确执行'改变=真;'如果它真的会导致do-while永远运行 – Vihar
如果你想对数组进行排序,你可以使用Arrays.sort(arrayN);' – kaykay