简体   繁体   中英

How to find the sum of all the numbers entered before or after finding the Sorted array list?

I have written a program in ArrayList to find the sorted array. But I have to find the sum of the numbers entered as well.

I couldn't succeed in getting the results as it is in the array list

import java.util.ArrayList;
import java.util.Scanner;

public class project1 {

public static void main(String[] args) {

int add = 0;
    Scanner input = new Scanner(System.in);
    System.out.print("Enter 5 numbers: ");
    ArrayList<Integer> list = new ArrayList<>();
    for (int i = 0; i < 5; i++) list.add(input.nextInt());

    System.out.println("add" +add);
    System.out.println("Sorting numbers...");
    sort(list);
    System.out.println("Displaying numbers...");
    System.out.println(list);

}

public static void sort(ArrayList<Integer> list) {
    for (int i = 0; i < list.size() - 1; i++) {
        int currentMin = list.get(i);
        int currentIndex = i;

        for (int j = i + 1; j < list.size(); j++) {
            if (currentMin > list.get(j)) {
                currentMin = list.get(j);
                currentIndex = j;
            }
        }

       if (currentIndex != i) {
            list.set(currentIndex, list.get(i));
            list.set(i, currentMin);
        }
    }
}
}

I am looking to get the sum of the entered numbers along with sorting. Any help will be very appreciated.

change this

    for (int i = 0; i < 5; i++) list.add(input.nextInt());

to this

    int sum  = 0;

    for (int i = 0; i < 5; i++){
      int num = input.nextInt();
      list.add(num);
      sum += num;
   } 

the value of the sum is saved inside sum and you can do what ever you want with it. I am using the For loop to add the values the user entered to a var name sum that is located out side of the for loop and when the for loop is done you have the sum

你可以在for (int i; ...循环的底部写sum += currentMin 。这样你就可以将每个数字精确计算一次,在它放在最后的位置之后。

 ArrayList<Integer> list = new ArrayList<>();
int sum = 0
for (int i = 0; i < 5; i++) {
int in = input.nextInt();
sum = sum + in;
list.add(in);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM