这个程序正在运行,但不是我喜欢的方式。我能够计算最大值,但我必须首先定义参数的数量。我希望能够输入可变数量的参数,然后返回最大值。 我该怎么办?
public static void main(String[] args) {
Scanner cin=new Scanner(System.in);
int n=cin.nextInt();
int max=cin.nextInt();
for(int i=2; i<=n; i++){
int num=cin.nextInt();
if(num>max) max=num;
}
System.out.println(max);
}
答案 0 :(得分:2)
我想你想在不给出输入数量作为第一个参数的情况下得到最大值。
calc max
public static void main(String[] args) {
Scanner cin=new Scanner(System.in);
String input=cin.nextLine();
String[] numbers = input.split("\\s");
int max = Integer.parseInt(numbers[0]);
for(int i=1; i<numbers.length; i++){
int num=Integer.parseInt(numbers[i]);
if(num>max) max=num;
}
System.out.println(max);
}
答案 1 :(得分:0)
这是我的猜测,你可以告诉我这是你想做的。
public static void main(String[] args) {
//Your tokenizer
Scanner scanForNumbers = new Scanner(System.in);
//First prompt for number of numbers
System.out.print("Print the Number of Numbers to Enter:");
int numberOfNumbers = scanForNumbers.nextInt();
System.out.println();
int maxOfNumbers = 0;
int tempNum = 0;
//making number of numbers the max iterate till you get there.
for(int index = 0 index < numberOfNumbers; index++){
//Prompt for a number
System.out.print("Enter another Number");
tempNum = scanForNumbers.nextInt();
System.out.println();
//if it is bigger, set a new max.
if(tempNum > maxOfNumbers){
maxOfNumbers = tempNum;
}
}
System.out.println("The Bigger Number is : " + maxOfNumbers);
}