忽略Java Arraylist中的负值进行计算

问题描述 投票:1回答:3

我的代码的想法是,它向用户询问每个月的收入,直到用户输入负值为止,该负值不应添加到总收入中,而应在输出中显示,但在计算中将其忽略。然后,代码将计算总收入(忽略最后一个负值),平均收入(忽略负值)以及所有值的最大/最大值。我没有任何问题可以确定最大的价值。但是我怎么能忽略计算中的负收入,而maby甚至根本不将其添加到数组中?

问题是该计算还将负值/收入也添加到总和和平均收入计算中。并且它不会忽略负收入的月份。

到目前为止是我的代码:


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));
        }







    }


java arraylist negative-number
3个回答
2
投票

尽管您确实在计算中加入了最后一个负数,但这不是代码无法正常工作的最终原因。您实际上正在检查您读取的上一个


0
投票

我想这就是您要寻找的。


0
投票

您可以使用Integer.signum(int)函数来知道该值是负数(返回值= -1)还是零(返回值= 0)还是正数(返回值= 1)。因此,基本上忽略if Integer.signum(income) == -1

© www.soinside.com 2019 - 2024. All rights reserved.