So I'm working on a project currently and this step asked me to write a program which asks for numbers and when "-1" is entered, it will calculate the sum of all numbers entered except the -1. I simply fixed this by adding +1 after the loop, but im sure there is another "proper" way of doing it and i would like to learn how.
Any help is appreciated. ( Note: I've only been learning Java for around a week so ELI5 please )
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int numbertyped = 0;
int sum = 0;
System.out.println("Type numbers: ");
while (numbertyped != -1) {
numbertyped = Integer.parseInt(reader.nextLine());
sum = sum + numbertyped;
}
sum++;
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
EDIT: My program is complete now. I used the solution of adding a break in the while loop and after adding the rest of the features i wanted, this is the end product: ( if anyone has tips on how to improve my code or make it more efficient please comment! )
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-3
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int numbertyped = 0;
int sum = 0;
int howmany = 0;
int evencounter = 0;
int oddcounter = 0;
System.out.println("Type numbers: ");
while (true) {
numbertyped = Integer.parseInt(reader.nextLine());
if (numbertyped == -1)
{
break;
}
if (numbertyped % 2 == 0)
{
evencounter++;
}
else
{
oddcounter++;
}
sum = sum + numbertyped;
howmany++;
}
double average = (double) sum / howmany;
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + howmany);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + evencounter);
System.out.println("Odd numbers: " + oddcounter);
}
}