gpt4 book ai didi

java - 当使用扫描仪输入值到数组时找不到最小的数字

转载 作者:行者123 更新时间:2023-12-01 11:03:35 24 4
gpt4 key购买 nike

使用扫描仪:

import java.util.Scanner;

public class InputArrayFromScanner {

private static Scanner keyIn;

public static void main(String[] args) {
keyIn = new Scanner (System.in);
System.out.print("Enter a Number: ");
int inNum = keyIn.nextInt();
int [] arrNum = new int [inNum];
int maxNum = arrNum[0];
int minNum = arrNum[0];
int average = 0;
int total = 0;
for (int count : arrNum){
System.out.print ("> ");
arrNum[count] = keyIn.nextInt();
if (arrNum[count] > maxNum)
maxNum = arrNum[count];
else if (arrNum[count] < minNum)
minNum = arrNum[count];
total += arrNum[count];
average = total/arrNum.length;
}
System.out.print("\tBigest Number is:"+maxNum);
System.out.print("\tSmallest Number is:"+minNum);
System.out.print("\tPlus of Numbers is:"+total);
System.out.println("\tAverage Of Numbers is:"+average);


}

}

不带扫描仪

public class MinAndMax {

public static void main(String[] args) {
int [] arrNum = {10,12,80,6,5};
int minNum = arrNum [0];
int maxNum = arrNum [0];
for (int count = 0; count < arrNum.length; count++ ){
if (arrNum[count] < minNum)
minNum = arrNum[count];
else if (arrNum[count] > maxNum)
maxNum = arrNum[count];
}
System.out.print ("\tSmallest Number is "+minNum);
System.out.print ("\tBigest Number is "+maxNum);
}

}

问题是什么?

最佳答案

在第一个代码片段中,您将使用增强的 for 循环迭代数组值:

for (int count : arrNum)

您应该迭代数组索引:

for (int count = 0; count < arrNum.length; count++)

关于java - 当使用扫描仪输入值到数组时找不到最小的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33146911/

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