我正在撰寫一個程式,其中用戶輸入 n 個數字,程式找到輸入數字的數字總和,然后列印具有最大數字總和的數字。比如n=3,輸入的數字是325、800、199,那么程式應該列印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 正在按應有的方式更新。但麥克斯不是。
uj5u.com熱心網友回復:
Max正在更新中。你有max = a;,但此時a已經為零。這個回圈:
while (a>0) {
int d = a%10;
e = d;
a = a/10;
}
將繼續回圈直到a變為 0 或更少,這就是條件的a>0含義。達到時max = a;,唯一可能的值a為零。順便說一句,學習使用除錯器,它是你的朋友。
uj5u.com熱心網友回復:
意外的解決方案是由這條線引起的
a = a/10;
在某些時候,它會產生零。這正是退出while回圈的條件。所以你退出了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);
}
}
請記住,驗證輸入整數是否為正會很好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/457767.html
標籤:爪哇 变量 整数 java.util.scanner
