-1
import java.util.Scanner;

class Digitsdisplay {
public static void main(String args[]){
    Scanner input = new Scanner(System.in);

    System.out.println("Please enter a value: ");

    int value = input.nextInt();
    int total  = 0;
    String digit = "" + value;

    System.out.print("");

    for (int i = 0; i < digit.length(); i++) {
       int myInt = Integer.parseInt(digit.substring(i, i + 1));
       System.out.println(myInt);
       total += myInt;
    }

}
}

输出:请输入一个值: 789 7 8 9

如何反转输出?例如,当我输入数字 123 时,它会显示 321,每个数字换行。

4

4 回答 4

1

如果用户输入以 10 为底的值,则可以改为使用模运算符和整数除法来在 while 循环中连续获取最右边的值,如下所示:

import java.util.Scanner;

public class Digitsdisplay {
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);

        System.out.println("Please enter a value: ");

        int value = input.nextInt();
        int quotient = value;
        int remainder = 0;

        while(quotient != 0){
            remainder = quotient%10;
            quotient = quotient/10;
            System.out.print(remainder);
        }

    }
}

这可能是一种更好的方法,它尝试将 int 转换为字符串,然后逐个字符地遍历字符串。

于 2013-10-23T23:00:06.953 回答
0

循环打印以反向循环:

import java.util.Scanner;

class Digitsdisplay {
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);

        System.out.println("Please enter a value: ");

        int value = input.nextInt();
        int total  = 0;
        String digit = "" + value;

        System.out.print("");

        for (int i = digit.length()-1; i >= 0; i--) {
           int myInt = Integer.parseInt(digit.substring(i, i + 1));
           System.out.println(myInt);
           total += myInt;
        }

    }
}

编辑:没有理由反转字符串本身,即。像其他答案所说的那样使用 Stringbuilder 。这只是增加了运行时。

于 2013-10-23T22:24:59.167 回答
0
import java.util.*;

public class Francis {

    public static void main(String[] args) {
         Scanner input= new Scanner (System.in);
         System.out.println("Please enter a value: ");

    int value = input.nextInt();
    int total  = 0;
    String digit = "" + value;

    System.out.print("");

    for (int i = 0; i < digit.length(); i++) {
       int myInt = Integer.parseInt(digit.substring(i, i + 1));
       System.out.println(myInt);
       total += myInt;
    }
  }
}
于 2014-07-01T12:31:04.667 回答
-1

在循环之前简单地反转字符串

digit = new StringBuilder(digit).reverse().toString();
于 2013-10-23T22:25:09.443 回答