-1

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.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52

3 Answers3

0

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

Dor
  • 657
  • 1
  • 5
  • 11
0

You could just write sum += currentMin at the bottom of the for (int i; ... loop. This way you count every number exactly once, after it is put in its final place.

Feuerrabe
  • 11
  • 2
-1
 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);
 }
user3411846
  • 178
  • 1
  • 3
  • 13
  • @AbhishekDS Strange. This doesn't do what you asked. *I am looking to get the sum of the entered numbers along with sorting.* I don't see a sort anywhere? – WJS Jun 16 '19 at 16:18