smallest and largest of the inputs

喜夏-厌秋 提交于 2019-11-28 12:43:38

问题


I was assigned to write a program that read a sequence of integer inputs and print -the smallest and largest of the inputs -and the number of even and odd inputs

I figured out the first part but am stumped on how I can get my program to display the largest and the smallest. This is my code so far. How can I get it to display the smallest input aswell?

public static void main(String args[])
{
      Scanner a = new Scanner (System.in);
      System.out.println("Enter inputs (This program calculates the largest input):");

      double largest = a.nextDouble();
      while (a.hasNextDouble())
      { 
          double input = a.nextDouble();
          if (input > largest)
          {
              largest = input;
          }
      }


      System.out.println(largest);
}

回答1:


The simplest solution would be use something like Math.min and Math.max

double largest = a.nextDouble();
double smallest = largest;
while (a.hasNextDouble()) {
    double input = a.nextDouble();
    largest = Math.max(largest, input);
    smallest = Math.min(smallest, input);
}



回答2:


double largest = a.nextDouble();
double smallest = largest;
while (a.hasNextDouble()) {
    double input = a.nextDouble();
    if (input > largest) {
        largest = input;
    }
    if (input < smallest) {
        smallest = input;
    }
}



回答3:


Keep track of the smallest value in the same manner.

public static void main(String args[])
{
    Scanner a = new Scanner (System.in);
    System.out.println("Enter inputs (This program calculates the largest and smallest input):");

    double firstInput = a.nextDouble();
    double largest = firstInput;
    double smallest = firstInput;
    while (a.hasNextDouble())
    { 
        double input = a.nextDouble();
        if (input > largest)
        {
            largest = input;
        }
        if (input < smallest)
        {
            smallest = input;
        }
    }

    System.out.println("Largest: " + largest);
    System.out.println("Smallest: " + smallest);
    }
}


来源:https://stackoverflow.com/questions/15328779/smallest-and-largest-of-the-inputs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!