display count of times the number has been entered

Viewed 33

im doing an excercise, it wants to display the number of times the user has entered the number till he enter -1 which breaks the program. I can't think of a way to add it. I'd like you to add a variable which will store the number of times user entered a number and display it at the bottom

    System.out.println("Type numbers:");
    
    int sum = 0;
    
    while(true) {   
        int number = Integer.parseInt(scanner.nextLine());
        if(number == -1) {
            break;
        }
        
        sum += number;
        
    } 
    
    System.out.println("Thank you and see you later");
    System.out.println("The sum of the numbers is "+sum);
}   

}

1 Answers

Solution of the problem is already given in the comment section. I'm just adding it as an answer with code.

Solution:

Maintain another variable to count the number of given inputs.

Code:

System.out.println("Type numbers:");

int sum = 0;
int inputCount = 0;

while (true) {
    int number = Integer.parseInt(scanner.nextLine());
    if (number == -1) {
        break;
    }
    inputCount++;   // incrementing number of valid input
    sum += number;
}

System.out.println("Thank you and see you later");
System.out.println("The sum of the numbers is " + sum);
System.out.println("Count of given input " + inputCount);
Related