0

print two digit integer as two different number

int x=32;

how to split it as two individuals like:

int x=3;
int y=2;
R.Nav
  • 11
  • 1
  • 2

2 Answers2

0

You could convert the int to a String and then take the first and second characters. eg.

final int x = 32;
System.out.println("First digit:" + String.valueOf(x).charAt(0));
System.out.println("Second digit:" + String.valueOf(x).charAt(1));

For a general solution to integers of any length see the answers here: Return first digit of an integer

Community
  • 1
  • 1
ozOli
  • 1,414
  • 1
  • 18
  • 26
0

There are many ways you can do that. You could use basic math operations to do it as well. However here is another way you could go about solving this problem. That is by using the built in stack in java. Here's the code. Just try running it.

import java.util.Scanner;
import java.util.Stack;

public class test_driver{
    public static void main(String[] args){
        Stack<Integer> myStack = new Stack<Integer>();
        int n, r;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a number: ");
        n = in.nextInt();
        while(n != 0){
            r = n % 10;
            n = n / 10;
            myStack.push(r);
        }
        while(!myStack.isEmpty()){
            System.out.println(myStack.pop());
        }
    }
}

Hope it helped.

theprogrammer
  • 1,698
  • 7
  • 28
  • 48