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,每个数字。
答案 0 :(得分: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转换为字符串,然后逐字符循环字符串。
答案 1 :(得分: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说。这只会增加运行时。
答案 2 :(得分: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;
}
}
}
答案 3 :(得分:-1)
在循环之前简单地反转字符串
digit = new StringBuilder(digit).reverse().toString();