简体   繁体   中英

How to accept any number of more than two digits in Java?

I have to write a program that will accept any number of more than two digits and then display the reverse of that number. How should i write the code for the “accept any number of more than two digits” part?

This is my code:

import java.util.Scanner;
public class Reversenum
{
  public static void main(String args [])
    {
        int num, reversenum=0;
        System.out.println(“Input a number and press enter”);
        Scanner in= new Scanner(System.in);
        num= in.nextInt();

        for (;num!=0;)
        {
                reversenum= reversenum*10;
                reversenum= reversenum+num%10;
                num=num/10;
        }
        System.out.println(“Reverse number =“+reversenum);
      }
 }

Do this:

public static void main(String args []) {
    int num=0, reversenum=0;
    boolean flag = true;
    while(flag) {
        try {
            System.out.println("Input a number and press enter");
            Scanner in= new Scanner(System.in);
            num= in.nextInt();
            if(num>99) {
                break;
            }else {
                continue;
            }
        }catch (Exception e) {
            continue;
        }

    }

    for (;num!=0;)
    {
            reversenum= reversenum*10;
            reversenum= reversenum+num%10;
            num=num/10;
    }
    System.out.println("Reverse number ="+reversenum);
  } 

this will ask the user to enter a number with more than 2 digits until it has received the number

do {
    System.out.println(“Input a number and press enter”);
    num= in.nextInt();
} while(num < 100);

add this where you get your input number

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