[英]My array.sort that I'm using in netbeans, isn't sorting
I'm quite new to Java and recently I wanted to practice more. 我是Java的新手,最近我想练习更多。 So I stumbled in this. 所以我偶然发现了这个。 I wanted to print out all the values in the array using Array.sort, but all I get is: 1,2,3,4,5,6
instead of; 我想使用Array.sort打印出数组中的所有值,但是我得到的只是: 1,2,3,4,5,6
而不是; 22,51,67,12,98,34
. 22,51,67,12,98,34
。 Here is the code: 这是代码:
public static void main(String[] args) {
int[] array;
array =new int[6];
array[0]=22;
array[1]=51;
array[2]=67;
array[3]=12;
array[4]=98;
array[5]=34;
Arrays.sort(array);
int i;
for (i=0; i < array.length; i++){
array[i]= i+1;
System.out.println("num is"+array[i]);
}
You're refilling the elements in array[i]
inside the for
loop. 您要在for
循环内重新填充array[i]
的元素。 Just print the contents of the array: 只需打印数组的内容:
for (i=0; i < array.length; i++){
//remove this line since it's setting the value of (i+1) to array[i]
//array[i]= i+1;
//leave this line only
System.out.println("num is"+array[i]);
}
Or, use Arrays.toString
to display the content of your array: 或者,使用Arrays.toString
显示数组的内容:
//no for loop needed
System.out.println("Array data: " + Arrays.toString(array));
You could always use your own code, EG: 您始终可以使用自己的代码EG:
private void butgoActionPerformed(java.awt.event.ActionEvent evt) {
int nums[] = {13,6, 1, 25,18,12};
//Array is called "nums", holds random numbers and such
int place = 0;
int check = 0;
while (place < nums.length - 1) {
while (check < nums.length) {
// "Check" loops inside place and checks to see where larger
if (nums[place] > nums[check]) {
//Change To < For Descending
int temp = nums[place];
nums[place] = nums[check];
//"Check" swaps the values around
nums[check] = temp;
}
check++;
}
//"Place" tells loop when to stop and holds a value to be compared
place++;
check = place + 1;
}
place = 0;
//"Place" acts as a counter
while (place < nums.length) {
//Output Loop
txtout.append("\n" + nums[place] + "");
//"txtoutput" is the textarea (.append means to add to the text already there
place++;
//"\n" means new line
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.