0
在此先感謝。當我爲這個數組輸入一個最小值時,我無法弄清楚爲什麼我的代碼會給我帶來麻煩。它似乎保留最初的0值,但我不知道如何解決這個問題。 Max工作正常。我是否在程序的錯誤部分設置了最大值和最小值?另外,這是我對數組的第一次任務,所以我可能在稍後打印下標時遇到一些問題。數組返回0的最小值(目標是查找最大值和最小值)
再次感謝!
編輯 - 這就解決了這個問題,據我所知。感謝丹W.
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
System.out.print("Enter a new number. This will continue until "
+ "you reach the size of the array. ");
arrayOfNumbers[i] = keyboard.nextInt();
}
int max = arrayOfNumbers[0];
int min = arrayOfNumbers[0];
package program8;
import java.util.Scanner;
public class arrayPrint {
public static void main(String[] args) {
final int NUMBER_OF_ELEMENTS;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the amount of numbers the array will read in. ");
NUMBER_OF_ELEMENTS = keyboard.nextInt();
int arrayOfNumbers[] = new int[NUMBER_OF_ELEMENTS];
int max = arrayOfNumbers[0];
int min = arrayOfNumbers[0];
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
System.out.print("Enter a new number. This will continue until "
+ "you reach the size of the array. ");
arrayOfNumbers[i] = keyboard.nextInt();
}
for (int i = 0; i < arrayOfNumbers.length; i++) {
if (max <= arrayOfNumbers[i])
max = arrayOfNumbers[i];
}
for (int i = 0; i < arrayOfNumbers.length; i++) {
if (min >= arrayOfNumbers[i])
min = arrayOfNumbers[i];
}
System.out.print(+max+ "max and " +min+ " min");
}
}
像上面那樣? (我不知道如何在評論中放置代碼,但它沒有看起來很糟糕,所以它在編輯中,在原始代碼之上。我是這樣工作的。我之前已經嘗試過,但它沒有工作,因爲我在它之內第一個for循環的括號,謝謝!看起來是否正確? – user1082706
是的,我當時只輸入正數,謝謝 – user1082706
是的,這看起來不錯,希望它可以工作,請接受答案,如果這解決了您的問題 –