Home > other >  Trouble printing an int value user entered
Trouble printing an int value user entered

Time:11-24

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 :

    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"

CodePudding user response:

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);
  • Related