简体   繁体   English

如何在Java中分别打印两位数的数字?

[英]How to print the digits of a two digit number separately in Java?

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;

You could convert the int to a String and then take the first and second characters.您可以将 int 转换为 String,然后取第一个和第二个字符。 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有关任何长度整数的一般解决方案,请参阅此处的答案: 返回整数的第一位

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.那是通过使用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.希望它有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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