Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trouble printing an int value user entered

So I’m building a program that reads user input in integers and adds the value of all the integers togther

My main method is :

public static void main(String[] args) {

My current code is :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    Scanner scanner = new Scanner(System.in); // imports scanner
     
           
    System.out.print("Enter an number: "); // ask user to enter number 

    // Repeat until next item is an integer
    while (!scanner.hasNextInt()) 
    {        
        scanner.next(); // Read and discard offending non-int input or int + not int input
        System.out.print("Please enter digits only: "); //  tells user to enter again 
    }

    // if user enters int , exits while loop 

    
     //adds ints entered
     int userNumber = scanner.nextInt(); // Gets the int 
        int sumofUsernumber = (0);
        while (userNumber > 0) {
            sumofUsernumber = sumofUsernumber + userNumber % 10;
           userNumber = userNumber / 10;
        }
        System.out.println("The combined value of " + userNumber + (" is ") + sumofUsernumber)

In the last line it supposed to print ther number the user enetered then the sum of the number, instead it prints, 0.

For example : if user enters 101 I’m trying to get it to print
"The combined value of 101 is 2"
Instead it prints
"The combined value of 0 is 2"

>Solution :

You need to store userNumber in some other variable as you are mutating the input from user directly.

The following code will help you

    // adds ints entered
    int userNumber = 101;
    int temp = userNumber;
    int sumofUsernumber = 0;
    while (temp > 0) {
      sumofUsernumber = sumofUsernumber + temp % 10;
      temp = temp / 10;
    }
    System.out.println("The combined value of " + userNumber + (" is ") + sumofUsernumber);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading