所以我现在有了这个代码。它运行,但它不按升序排列数字,我不知道应该做什么。我是java的新手......
import javax.swing.JOptionPane;
public class ThirdClass
{
public static void main (String args[]){
int a = 0;
int b;
int numbers;
int length = Integer.parseInt(JOptionPane.showInputDialog (null, "Input set size", JOptionPane.QUESTION_MESSAGE));
int ctr = 1;
int num[] = new int[length];
for(int i = 0; i < length; i++){
num[i] = Integer.parseInt(JOptionPane.showInputDialog (null, "Enter number " + ctr, JOptionPane.QUESTION_MESSAGE));
ctr++;
}
for(int i = 0; i < length; i++){
for(int j = i+1; j < length; j++){
if(num[i]<num[j]){
a = num[i];
num[i] = num[j];
num[j] = a;
}
}
}
for(int i = 0; i < length; i++){
JOptionPane.showMessageDialog (null, "Output: " + num[i] , "Value", JOptionPane.INFORMATION_MESSAGE);
}
}
}
答案 0 :(得分:3)
您似乎正在尝试进行冒泡排序,但您的逻辑有点偏差。将您的双for
循环更改为:
for (int i=0; i < length; ++i) {
for (int j=1; j < (length-i); ++j) {
if (num[j-1] > num[j]){
a = num[j-1];
num[j-1] = num[j];
num[j] = a;
}
}
}
答案 1 :(得分:2)
您不需要更改完整的逻辑。只需要将符号改为小于大于 检查以下代码。
for(int i = 0; i < length; i++){
for(int j = i+1; j < length; j++){
if(num[i]>num[j]){
a = num[i];
num[i] = num[j];
num[j] = a;
}
}
}