我制作了一个Java命令行程序来计算任意数字序列的总和和平均值,但是我想知道是否有更好的方法来使它更短并且可能没有数组?
public class Main {
public static void main(String[] args) {
System.out.println("------------------");
System.out.println("Program for calculating sum and average of an arbitary series of numbers");
System.out.println("------------------");
Scanner input = new Scanner(System.in);
System.out.print("How many numbers do you want to calculate? ");
int nums = input.nextInt();
int array[] = new int[nums];
int sum = 0;
for (int i=0; i<nums; i++){
System.out.print("Enter " + (i+1) + ". number: ");
array[i] = input.nextInt();
}
for (int i=0; i<array.length; i++){
sum= sum + array[i];
}
System.out.println("Sum is: " + sum);
System.out.print("Average is: " + (sum/nums));
}
}
答案 0 :(得分:2)
您的代码中有两个for循环。第一个将值写入数组,第二个读取值以获取它们的总和。您实际上并不需要两个循环(或数组)。您可以在读取值时对其求和,然后根据该总和计算平均值。
但是请注意,如果您想稍后扩展代码以计算输入数据的其他统计信息(例如标准差),则使用存储在数组中的数据将更加容易。
答案 1 :(得分:1)
在这种情况下,使用BufferedReader的费用比使用Scanner便宜。请参阅reasons to consider using BufferedReader。
public static void main(String[] args) throws IOException {
System.out.println("------\nProgram for calculating sum and average of integers\n------");
System.out.print("Enter space separated integer values: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] split = reader.readLine().split("\\s");//splits string on whitespaces
double sum=0, average;
for (String numberString : split)
sum += Integer.parseInt(numberString);
average = sum / split.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
}
答案 2 :(得分:0)
一种简单的解决方案,用户不必先输入数字。
public static void main(String[] args) {
System.out.println("------------------");
System.out.println("Program for calculating sum and average of an arbitary series of numbers");
System.out.println("------------------");
Scanner input = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
System.out.print("Input numbers. Input something else (e.g. enter) if you're finisehd:\n");
while (true) {
try {
values.add(Integer.parseInt(input.nextLine()));
} catch (Exception e) {
break;
}
}
System.out.println("Sum is : " + values.stream().mapToInt(Integer::intValue).sum());
System.out.println("Average is: " + values.stream().mapToInt(Integer::intValue).average().getAsDouble());
}