为什么数组中的最小值始终为0?

时间:2013-06-26 00:50:25

标签: java minimum

import java.util.Scanner;

public class Testing {
public static void main(String[] args){
    int[] userInput = new int[8]; 
    int userDetermint,numEntered;

    Scanner csole = new Scanner(System.in);

    System.out.print("Choose how many numbers you wanted to input the limits is up to 9: ");
    userDetermint = csole.nextInt();
    System.out.println("Please Key In Your "+ userDetermint + " numbers: ");
    for (int i = 0; i < userDetermint; i++ ){
        numEntered = csole.nextInt();
        userInput[i]= numEntered;
    } 
    int smallest = userInput[0];
    int largest = userInput[0];
    for ( int index = 0; index < userInput.length; index++ ){
        if(userInput[index]>largest)
            largest  = userInput[index];
        else if (userInput[index]< smallest)
            smallest = userInput[index];
    }
    System.out.println("Largest Number is "+ largest);
    System.out.println("Smallest Number is "+ smallest);
}

}

通过查找用户从2到10输入的最大值和最小值进行了练习。我使用数组来查明它但不知何故最小的值总是返回我0.想知道是否有人可以帮我指出错误并向我解释。

1 个答案:

答案 0 :(得分:2)

这一行

for ( int index = 0; index < userInput.length; index++ ){

应该是

for (int i = 0; i < userDetermint; i++ ){

或者您将循环进入0区域。