我正在尝试创建一个程序,将用户输入的整数从最大到最小排序。另外,我需要找到一种方法来打印最大和最小数字。当我定义了值时,代码排序正常,但现在我已将其切换为用户输入,由于某种原因它会发回“0”。这是我的代码
import java.util.Scanner;
public class SortInteger {
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please input three numbers");
int num = input.nextInt();
int number [] = new int [num]; //Sorting Array
int temp;
boolean correct = false; // Forces the sorting to continue till the numbers are in order
while(correct ==false){
correct = true;
for(int i = 0; i>number.length-1; i++ ){
if(number [i] > number [i+1]){
temp = number [i+1];
number [i+1] = number[i];
number[i]= temp;
correct = false;
}
}
}
for(int i = 0; i<number.length-1; i++){ //outputs the array to user
System.out.println(number[i]);
}
}
}
答案 0 :(得分:2)
您只是在初始化阵列。您从未使用元素初始化数组,因此您的数组元素将获得默认值。
System.out.println("Please enter size");
int num = input.nextInt();
int number [] = new int [num]; //Sorting Array
for(int i=0; i<number.length; i++){
System.out.println("Please enter element at index " + i);
number[i] = input.nextInt()
}
答案 1 :(得分:2)
你只拍了一个号码
int num = input.nextInt();
并且您正在将它用于数组大小:
int number [] = new int [num];
但是在其余代码中你没有接受任何输入,所以你的数组是空的。
代码::
import java.util.*;
class test{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please input three numbers");
int num1 = input.nextInt();
int num2 = input.nextInt();
int num3 = input.nextInt();
int number [] = {num1,num2,num3}; //Sorting Array
int temp;
boolean correct = false; // Forces the sorting to continue till the numbers are in order
while(correct ==false){
correct = true;
for(int i = 0; i<number.length-1; i++ ){
if(number [i] > number [i+1]){
temp = number [i+1];
number [i+1] = number[i];
number[i]= temp;
correct = false;
}
}
}
for(int i = 0; i<number.length; i++){ //outputs the array to user
System.out.println(number[i]);
}
}}
输出:
Please input three numbers
1
5
4
1
4
5
答案 2 :(得分:1)