用java语言编写一程序来接受用户输入的5个整数值,把这些数存放到一个数组中,正、倒序输出,并输出最大值

如题所述

import java.util.Scanner;

public class Test{
public static void main(String[] ars){
int[] arr = new int[5];
Scanner in = new Scanner(System.in);
int max = 0;
for(int i = 0;i<5;i++){
arr[i] = in.nextInt();
if(max<arr[i])
max = arr[i];
}

System.out.println("max = "+max);
for(int i = 4;i>=0;i--)
System.out.print(arr[i]+"\t");
}
}
运行结果:
若输入 1 2 3 4 5
结果如下:
max = 5
5 4 3 2 1

希望对你有帮助。。。。
温馨提示:内容为网友见解,仅供参考
第1个回答  2011-03-10
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;

public class ABC {

public static void main(String[] args) throws Exception {

final int count = 5;
int[] ary = getInput(count);

Arrays.sort(ary);

System.out.println("Integer numbers inputed in ASC order is: ");
for(int value: ary){
System.out.print(value + "\t");
}

System.out.println("\nInteger numbers inputed in DESC order is: ");

for(int i = ary.length; i > 0; i--){
System.out.print(ary[i-1] + "\t");
}

int max = ary[ary.length-1];
System.out.println("\n\nMax of the input is: " + max);
}

private static int[] getInput(int count) {
int[] ary = new int[count];

int i = 0;

while(i < count){
boolean isValidInput = true;

while(isValidInput){
try{
System.out.print("Please input an integer for number " + (i+1) + ": ");
Scanner scanner = new Scanner(System.in);

ary[i] = scanner.nextInt();
i++;
isValidInput = false;
}catch(InputMismatchException mismatchExp){
System.out.println("Only int value allowed. Please input an integer: ");
}
}

}

return ary;
}
}

--------------------------------
Please input an integer for number 1: 25
Please input an integer for number 2: aa
Only int value allowed. Please input an integer:
Please input an integer for number 2: 369
Please input an integer for number 3: 23.355
Only int value allowed. Please input an integer:
Please input an integer for number 3: 128
Please input an integer for number 4: 648
Please input an integer for number 5: 9978
Integer numbers inputed in ASC order is:
25 128 369 648 9978
Integer numbers inputed in DESC order is:
9978 648 369 128 25

Max of the input is: 9978
第2个回答  2011-03-25
加个for循环
相似回答