简体   繁体   English

程序不会输出最低的数字[Java]

[英]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. 我将highestNumber和lowestNumber初始化为数组中的第一个元素。 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. 除了将索引值与最小数字进行比较的if语句外,其他所有方法都起作用。 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). 它与最高数字的if语句相反(顺便说一句)。 The program always returns 0.0 for the lowest number. 程序始终为最小数字返回0.0。 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] . 请注意如何将最高和最低初始化为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. 此时,它们都为0。当您浏览数字列表时,没有任何事物会低于0(假设您仅输入正数),因此0将是您的输出。 I suggest initializing it to Integer.MAX_VALUE instead - every int by definition is lower then this. 我建议改为将其初始化为Integer.MAX_VALUE根据定义,每个int都比该值低。 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. 同样,您可能希望将highestNumber = number[0]更改为highestNumber = Integer.MIN_VALUE该值不小于任何值,这将使您的程序也可以处理负数。

I initialized highestNumber and lowestNumber to the first element in the array. 我将highestNumberlowestNumber初始化为数组中的第一个元素。

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. 问题是,您已经在number[0]元素获得其第一个有意义的值之前进行了分配,而是存储了默认值。 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. **请注意,除了在用户实际输入number [0]的值之前通过number [0]初始化maximumNumber和lowestNumber之外,您的所有代码都很好,因此请在用户为number [0]输入值的循环中使用这些初始化语句当index = 0时。 That's all.It'll work cause I tested in my PC,so,try it. 就是这样。因为我在PC上进行了测试,所以可以尝试一下。

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. 我对Java不太了解,因此请考虑以下内容为伪代码。 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);
        }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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