我一直在編寫一個(gè)簡(jiǎn)單的 Java 代碼,您可以通過控制臺(tái)向程序提供 5 個(gè)數(shù)字,然后程序會(huì)告訴您選擇了哪些數(shù)字并給出平均值。然而,我注意到,在我開始嘗試測(cè)試我的代碼后,for 循環(huán)基本上“跳過”了循環(huán)內(nèi)的所有代碼,我不知道為什么。這是我的代碼:import java.util.Scanner;public class numAv {public static void main(String[] args) { int num; int[] numbers = new int[5]; boolean done = false; Scanner scan = new Scanner(System.in); System.out.println("Enter five integer numbers one at a time."); for (int i = 0; i >= 5; i++) { scan.nextLine(); num = scan.nextInt(); numbers[i] = num; } // The code inside the for loop is being skipped; I'm not getting any time to type in an integer. System.out.println("Your numbers are:"); for (int i = 0; i >= 5; i++) { System.out.print(numbers[i]); } // The same has also happened above; The code within the for loop is essentially being skipped. num = 0; for (int i = 0; i >= 5; i++) { num += numbers[i]; } num /= (float) 5; System.out.println("The average of the chosen numbers is " + num);}}這是控制臺(tái)輸出的內(nèi)容:Enter five integer numbers one at a time.Your numbers are:The average of the chosen numbers is: 0
2 回答

郎朗坤
TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊
這里:
for (int i = 0; i >= 5; i++) {
i
同時(shí)為零和大于 5 會(huì)很難。
真正的答案是:您放入源代碼中的每個(gè)字符都很重要。<=
和之間存在很大差異>=
,甚至 和<=
之間也存在很大差異<
。因此,當(dāng)您的代碼沒有執(zhí)行您期望的操作時(shí):拿一張紙,然后開始手動(dòng)“運(yùn)行”該代碼。真正寫下變量中的值,并仔細(xì)檢查代碼對(duì)它們的作用。

函數(shù)式編程
TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊
狀況不佳:
for (int i = 0; i >= 5; i++) {
這永遠(yuǎn)不會(huì)起作用,試試這個(gè):
for (int i = 0; i < 5; i++) {
添加回答
舉報(bào)
0/150
提交
取消