AppSensei
AppSensei

Reputation: 8400

Separate the digit in an Integer (User-Input)

How do I enter a digit like '23423' and output it like '2 3 4 2 3'? And how do I make it so that user cannot enter less or more than 5-digits? (Your help would be appreciated. I just need hints from you guys since I'm learning Java. Looking forward to learn something new.)

This is what I have so far:

    Scanner input = new Scanner(System.in);

    int value1, value2, value3, value4, value5;

    System.out.print("Enter a number: ");
    value1 = input.nextInt();

    System.out.print("Enter a number: ");
    value2 = input.nextInt();

    System.out.print("Enter a number: ");
    value3 = input.nextInt();

    System.out.print("Enter a number: ");
    value4 = input.nextInt();

    System.out.print("Enter a number: ");
    value5 = input.nextInt();

    System.out.printf(" %d " + " %d " + " %d " + " %d " + " %d\n ", value1, value2, value3, value4, value5);

Upvotes: 0

Views: 1460

Answers (3)

metaman
metaman

Reputation: 69

The most appropriate solution seem to me a while loop where you build a string and add a space. In the aftermath of the while processing you should eliminate the last space. Something like the following should fit your needs. I have used the apache commons project, but you also utilize your own class.

    Scanner scanner = new Scanner(System.in);

    String str = "";
    while (scanner.hasNext()) {
        String next = scanner.next();
        if (next.equals("E")) {
            break;
        }

        if (NumberUtils.isNumber(next)) {
            for (int i = 0; i < next.length(); i++) {
                str += Integer.valueOf(next.substring(i, i + 1)) + " ";
            }
        }
    }
    str = str.substring(0, str.length() - 1);

    System.out.println("your number: " + str);  

With "E" you can exit the loop.

Upvotes: 0

jmoreno
jmoreno

Reputation: 13561

If you really want them to enter a single 5 digit number, you're going to have to do validation on the users input and then give an error if the input isn't valid. If the requirements are such that the first digit of your 5 digit number should never be zero, you can just get an int and then check if it is greater than 9999 and less than 100000. Otherwise take it as a string and check the length, then turn it into an integer once you have validated it.

Upvotes: 2

Renan
Renan

Reputation: 462

It can be redone with a loop: make the loop read the input 5 times and, each time, put the i-th read value at the i-th position of an array.

Then, to print it, you can just use a for loop that prints each element of the array.

Upvotes: 3

Related Questions