简体   繁体   English

从扫描仪拉出的整数的最后一位开始一个for循环(java)

[英]starting a for loop on the last digit of an integer pulled from a scanner (java)

I'm trying to get a for loop to start on the last digit of an integer that is given by the user through scanner. 我试图让一个for循环开始在用户通过扫描仪给出的整数的最后一位数字上。 Any suggestions? 有什么建议么?

for(int i = number.length()-1;...)

I'm looking for something along those lines but that won't leave me with a compile error 我正在寻找这些方面的东西,但这不会给我带来编译错误

You must convert the number to a String then iterate through each character. 您必须将数字转换为String然后遍历每个字符。

public class IterateNumber {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter a number:");
        String num = String.valueOf(scanner.nextInt());

        for(int i = num.length()-1; i >= 0; i--){
            System.out.println(num.charAt(i));
        }
    }
}

Use integer arithmetic: 使用整数运算:

for (int i = number, digit = i % 10; i > 0; i = i / 10, digit = i % 10) {
    // do something with "digit", which will iterate from last digit to first 
}

Here's some sample code showing it working: 以下是一些显示其工作的示例代码:

int number = 1234567890;
for (int i = number, digit = i % 10; i > 0; i = i / 10, digit = i % 10) {
    System.out.println(digit);
}

Output: 输出:

0
9
8
7
6
5
4
3
2
1

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

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