简体   繁体   中英

Method to sum and reverse a single input in Java?

斜体粗体 ►缩进代码4个空格►反引号转义, like _so_通过在行首添加>进行引用►进行链接

There is something wrong with your code:

You never put user input inside num array and for loop was just an active wait,

try it now:

public static void main(String[] args) 
            {
                //call for input
                System.out.println("Please Enter a 3-digit number..");
                Scanner in = new Scanner(System.in);
                int val = in.nextInt();
                int[] num = new int[3];
                if(val<=99) // is not a 3 digit number
                   return;

                int i =2;
                while (val > 0) {
                   num[i]=(val%10);
                   val = val / 10;
                   i--;
                }
                System.out.println("The Sum of the numbers is " + (num[0] + num[1]+ num[2]));
                System.out.println("The Reverse of the numbers is " + num[2] +""+ num[1]+""+ num[0]);

            }

With input 1 - 2 -3 gives you:

Please Enter a 3-digit number..
1
2
3
The Sum of the numbers is 6
The Reverse of the numbers is 321

try this

    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int sum = 0;
    int rev = 0;
    while (n > 0) {
        int rem = n % 10;
        sum += rem;
        rev = rev * 10 + rem;
        n = n / 10;
    }
    System.out.println("The Sum of the numbers is " + sum);
    System.out.println("The Reverse of the numbers is " + rev);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM