【发布时间】:2020-01-11 12:30:38
【问题描述】:
我的代码的想法是它询问用户每个月的收入,直到用户输入负值,它不应该添加到总收入中并且应该显示在输出中,但在计算中被忽略。 然后代码计算总收入(忽略最后一个负值)、平均收入(忽略负值)和所有值的最大/最大值。我没有问题得到正确的最大值。但是我怎么能忽略计算中的负收入,甚至根本不将它添加到数组中呢?
问题在于,该计算还将负值/收入添加到总和和平均收入计算中。并且不忽略负收入的月份。
到目前为止,这是我的代码:
package income;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Income {
public static void main(String[] args) {
int sum = 0;
int months = 0;
Scanner input = new Scanner(System.in);
System.out.println("Write the income of each month.");
ArrayList<Integer> array = new ArrayList<Integer>();
System.out.println("Write the income of month 1: ");
int income = input.nextInt();
sum += income;
months++;
array.add(income);
while(true){
months++;
System.out.println("Write " + months + ". month income: ");
if(income >= 0){
income = input.nextInt();
sum += income;
array.add(income);
}
else if (income < 0){
break;
}
}
/*This did not work
for(int i= 0; i < array.size(); i++){
if(income < 0){
array.remove(i);
}
}*/
months--;
System.out.println("The total income is " + sum);
System.out.println("The average income is " + sum/months);
//This one below works fine
System.out.println("The biggest income is " + Collections.max(array));
}
}
【问题讨论】:
-
为什么还需要将最后一个负值添加到列表中?
-
这个想法是,当我添加负值时,它不再要求更多的值,而是计算和打印这些东西:总收入、平均收入和最大收入。
-
任何计算都需要负值吗?
-
我不想将负值添加到列表中,但不知道如何成功避免它。我需要数组列表来使用 Collections 框架。我根本不需要负值来计算。
-
如果你不关心负值而不是作为一个停止器,你可以只反转 if 条件而不将值添加到列表中。
标签: java arraylist negative-number