gpt4 book ai didi

java - 在Java中的新行上打印数字的每个数字

转载 作者:行者123 更新时间:2023-11-30 08:07:29 25 4
gpt4 key购买 nike

我编写了以下代码,目的是让用户输入一个数字,即 123,程序将垂直输出为 1 2 3。无论我做什么,我的程序都按照 3 2 1 的方式执行。我需要在这个程序中使用循环,但我似乎无法弄明白。

import java.util.Scanner;

public class DigitsDisplay {
public static Scanner console = new Scanner(System.in);

public static void main(String[] args) {
int a = getInt("Give a non-negative integer: ");
double backwards = 0;
int reverse;
int numOfDigits = numOfDigits(a);
double place = Math.pow(10, numOfDigits);

while (a != 0) {
reverse = a % 10;
backwards = backwards + place * reverse;
System.out.println(reverse);
a = a / 10;
}
}

public static int getInt(String prompt) {
int input;

System.out.print(prompt);
input = console.nextInt();

return input;
}

public static int numOfDigits(int a) {
int numOfD = (int)(Math.log10(a)) + 1;

return numOfD;
}

}

最佳答案

反转反转的值

您的程序旨在反转数字。确实如此。如果你想反转它们,我建议你将它们附加到 StringBuilder然后 reverse那。喜欢,

StringBuilder sb = new StringBuilder();
while (a != 0) {
reverse = a % 10;
sb.append(reverse).append(System.lineSeparator());
backwards = backwards + place * reverse;
a = a / 10;
}
System.out.print(sb.reverse());

使用正则表达式

您的算法可以通过使用 String.replaceAll(String, String) 来简化用regular expression匹配 a 的所有数字并将其分组,然后将每个数字替换为自身加上新行。类似的东西,

int a = getInt("Give a non-negative integer: ");
System.out.println(String.valueOf(a).replaceAll("(\\d)",
"$1" + System.lineSeparator()));

关于java - 在Java中的新行上打印数字的每个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33684571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com