gpt4 book ai didi

java - 分析两位数并打印其各个数字的总和

转载 作者:行者123 更新时间:2023-12-02 06:16:01 26 4
gpt4 key购买 nike

我正在尝试制作一个可以分析用户的两位数字的程序。我使用 Scanner 对象来获取输入,然后使用数组组合。这是我的代码:

class Calculate {
public static void calculate() {
Scanner br = new Scanner(System.in);

int[] c = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int[] d = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

int sum;
int a = br.nextInt();
System.out.println("Digit is:" + a);

for (int i = 0; i < 10; i++) {
int e = 0;
if (a == ((c[i] * 10) + d[e])) {
sum = ((c[i] * 10) + d[e]);
System.out.println("First digit is:" + c[i]
+ " Second digit is:" + d[e]
+ "\n" + "Sum of digits=" + sum);
} else if (i == 9) {
i = 0;
e++;
} else if (e == 10) {
System.out.println("INVALID NO. HAS BEEN DETECTED");
}
}
}
}

我的预期输出(例如,如果用户输入 56):

Digit is:56 
First Digit:5 Second digit:6
Sum of digits=11

但是,输出没有正确输出;它接受无限的输入。像这样:

56
Digit is:56
23
89
45
.....

这样一来,它就陷入了循环。我该如何纠正这个问题?

最佳答案

如果您想获取数字的第一个和第二个数字,请使用此技术,而不是使用疯狂的 for 循环。

int number = 457;
int hundredsDigit = number % 1000 - number % 100;
int tensDigit= number % 100 - number % 10
int onesDigit = number % 10 - number % 1;

你看到这个模式了吗?

关于java - 分析两位数并打印其各个数字的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21461762/

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