变量未在Java中更新



我正在编写一个程序,用户在其中输入n个数字,该程序找到输入数字的位数之和,然后打印位数之和最大的数字。例如,n=3,并且输入的数字是325800199,那么程序应该打印199,作为1+9+9=19,这是800和325中最大的。

''

import java.util.Scanner;
public class maxi {
public static void main(String[] args) {
Scanner f = new Scanner(System.in);
System.out.println("Enter n: ");
int n = f.nextInt();
int max = 0;
int c = 0;
for (int i=0; i<n; i++) {
System.out.println("Enter a number: ");
int a = f.nextInt();
int e = 0;
while (a>0) {
int d = a%10;
e += d;
a = a/10;
}
if (e>c) {
c = e;
max = a;
}
}
System.out.println(max);
}
}

''

我面临的问题是变量max没有更新。我试着在for循环中打印e(数字总和(和c(最大数字总和(,它们运行良好,c正在按原样更新。但马克斯不是。

Max正在更新。您有max = a;,但此时a已经为零。此循环:

while (a>0) {
int d = a%10;
e += d;
a = a/10;
}

将保持循环直到a变为0或更小,这就是条件a>0的含义。当达到max = a;时,a的唯一可能值为零。顺便说一句,学会使用调试器,它是你的朋友。

这一行导致了意外的解决方案

a = a/10;

在某个时刻,它将产生零。这正是while循环退出的条件。当循环时,a等于0,然后将max赋值给0。

我的建议是为变量提供更多描述性的名称,并尝试以某种方式调试它。

按照类名称的注释-根据注释的上部CamelCase。

我修改了你的例子,这是许多可能的解决方案之一

public class Example {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter n: ");
int numberOfSamples = scanner.nextInt();
int result = 0;
int resultDigitSum = 0;
for (int i = 0; i < numberOfSamples; i++) {
System.out.println("Enter a number: ");
int inputNumber = scanner.nextInt();
int quotient = inputNumber;
int digitSum = 0;
do {
digitSum += quotient % 10;
quotient = quotient / 10;
}while(quotient > 0);
if (digitSum > resultDigitSum) {
resultDigitSum = digitSum;
result = inputNumber;
}
}
System.out.println(result);
}

}

请记住,最好验证输入整数是否为正。

最新更新