Friday 9 November 2018

Java - summing up Array list values



I am building an array that ask how many different inputs you have, then allowing you to enter each input. At the end I want to sum them up, but I keep getting an error.
Also when I go above 5 inputs, I lose one..... For example when I respond to the first question: Enter "10". When I start adding different numbers in it stops at nine. Please help.



public static void main(String[] args) {
Scanner input = new Scanner(System.in);



    System.out.println("Please enter the number of courses you have left: ");

int size = input.nextInt();
int[] numArr = new int[size];
System.out.println("Enter the number of CUs for each course: ");
for (int i=0; i {
numArr[i] = input.nextInt();
}
int totalSum = numArr + totalSum;
System.out.print("The sum of the numbers is: " + totalSum);


Answer



Change your logic and code to the following:



Scanner input = new Scanner(System.in);

System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
System.out.println("Enter the number of CUs for each course: ");
int totalSum = 0;
for (int i = 0; i < size; i++) {


totalSum+=input.nextInt();
}

System.out.print("The sum of the numbers is: " + totalSum);

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...