简体   繁体   中英

Program won't output the lowest number [Java]

I'm creating a program where users enter random numbers and it returns the highest and lowest number. I initialized highestNumber and lowestNumber to the first element in the array. Then I checked if the number was greater than or less than the value assigned for the respective variables. Everything works except the if statement that compares the value of the index to the lowest number. I'm not sure why it isn't working. It is the exact opposite of the if statement for the highest number (which works by the way). The program always returns 0.0 for the lowest number. Here is my main method:

private static String arrayLimit;
private static double highestNumber;
private static double lowestNumber;   

public static void main(String[] argument) throws IOException
{
    BufferedReader console =
        new BufferedReader(new InputStreamReader(System.in));

    System.out.print("How many numbers do you want to enter? ");
    arrayLimit = console.readLine();
    int limit = Integer.parseInt (arrayLimit);

    int[] number = new int[limit];

    highestNumber = number[0];
    lowestNumber = number[0];

    for (int index = 0; index < limit; index++)
    {
        System.out.print("Number " + (index + 1) + ": ");
        String input = console.readLine();
        number[index] = Integer.parseInt(input);

        if (number[index] > highestNumber)
        {
            highestNumber = number[index];
        }

        if (number[index] < lowestNumber)
        {
            lowestNumber = number[index];
        }
    } 
    System.out.println("Highest number: " + highestNumber);
    System.out.println("Lowest number: " + lowestNumber);
}

Note how you initialize highest and lowest to number[0] . At that point, they are thus both 0. When you go through the list of numbers, nothing will be lower than 0 (Assuming you only input positive numbers) and thus 0 will be your output. I suggest initializing it to Integer.MAX_VALUE instead - every int by definition is lower then this. Similarly, you might want to change highestNumber = number[0] to highestNumber = Integer.MIN_VALUE - the value that nothing is lower than, which will allow your program to handle negative numbers as well.

I initialized highestNumber and lowestNumber to the first element in the array.

No, you did not initialized these variables to the first element of the array: had you done that, your program would have worked fine. The problem is, you have made the assignment before the number[0] element got its first meaningful value, storing the default instead. That's why your program produced zero for the lowest number.

You can work around this problem by storing the index of the highest and the lowest number, instead of storing the number itself:

highestIndex = 0;
lowestIndex = 0;

for (int index = 0; index < limit; index++)
{
    System.out.print("Number " + (index + 1) + ": ");
    String input = console.readLine();
    number[index] = Integer.parseInt(input);

    if (number[index] > number[highestIndex])
    {
        highestIndex = index;
    }

    if (number[index] < number[lowestIndex])
    {
        lowestIndex = index;
    }
} 
System.out.println("Highest number: " + number[highestIndex]);
System.out.println("Lowest number: " + number[lowestIndex]);
for (int index = 0; index < limit; index++) {

    System.out.print("Number " + (index + 1) + ": ");

    String input = console.readLine();

    number[index] = Integer.parseInt(input);

      if(index == 0){     // here you initialize highestNumber & lowestNumber 

            highestNumber = number[0];

            lowestNumber = number[0];
        }        

    if (number[index] > highestNumber)
    {
        highestNumber = number[index];
    }

    if (number[index] < lowestNumber)
    {
        lowestNumber = number[index];
    }
} 

**Note that everything of your code is just fine except you initialized highestNumber and lowestNumber by number[0] before user actually inputs the value of number[0],so use these initialization statements in the loop where user inputs value for number[0] when index=0. That's all.It'll work cause I tested in my PC,so,try it.

I'll show you how I suggest structuring this code. My main point is that you should be using the array to structure your code, but since you're using an object-oriented language, I'll make it more object-oriented. I don't know much Java, so consider the following to be pseudocode. Some of the types may be wrong, some of the method names may be made up, etc.

class IntList {
  private final int[] numbers;
  private Integer highestNumber;
  private Integer lowestNumber;   

  public IntList(int [] numbers, boolean makeCopy)
    {
    highestNumber = null;
    lowestNumber = null;
    if(makeCopy)
      this.numbers = Arrays.copyOf(numbers, numbers.length);
    else
      this.numbers = numbers;
    }

  public static IntList getInput(BufferedReader reader, BufferedWriter writer)
    {
    writer.print("How many numbers do you want to enter? ");
    String arrayLimit = reader.readLine();
    int limit = Integer.parseInt (arrayLimit);
    int[] numbers = new int[limit];
    //Actually read in the numbers, using the reader and writer that were
    //passed in, rather than reaching out to System.
    return new IntList(numbers, false);
    }

  public int getHighest()
    {
      if(highestNumber!=null)
        return highestNumber;
      else
        ;//Find the highest number; set highestNumber to that value, then return that result.
    }

  public int getLowest()
    {
       //same idea here.
    }
}

public class Main {
  public static void main(String[] argument) throws IOException
  {
      //try-with-resources ensures that the reader gets closed properly. Since nothing
      //else happens in the program, this doesn't matter so much, but it's generally a good
      //habit to get into.
      try(BufferedReader console =
          new BufferedReader(new InputStreamReader(System.in)))
        {
        IntList list = IntList.getInput(console, System.out);
        System.out.println("Highest number: " + list.getHighest());
        System.out.println("Lowest number: " + list.getLowest);
        }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM