Question

I'm in intro to java and am stumped on this one challenge. I have searched my book and the helpful links on here but haven't found anything that pertains to what I'm doing.

The challenge is to create a list of numbers in a notepad file. The java program has to import the numbers, compare each number together, then print out what number in the list has the lowest value.

enter code here

here is my code

import java.io.*;
import java.util.Scanner;

/**
Aaron Moores
March 2, 2013
Input: Numbers file
Output: Highest number, lowest number
*/

public class LargenSmall
{
    public static void main(String[] args) throws IOException
    {
    String filename;        //Numbers file
    double lowest;

    //Open the file
    File file = new File("Number.txt");
    Scanner inputFile = new Scanner(file);

    lowest = 0.0;

    //Read all the values in Numbers file and find the lowest value
    while (inputFile.hasNext())
    {
    //Read a number in the file
    double number = inputFile.nextDouble();
    lowest =  < number;
    }

    //Close file
    inputFile.close();

    //Print out lowest value in the list
    System.out.println("The lowest number in your file called, " +
                            "Numbers.txt is " +lowest);
    }
}

My problem is figuring out how to format the code line that compares each value to store the lowest value. If I change (lowest = lowest < number) to (lowest = lowest + number) and add an accumulator the program will add all the values in my file and display them, so I know the import part of the program works. I'm just unclear on how to formulate a compare statement to have it display the lowest value.

please help I am stumped. Thanks

Was it helpful?

Solution 2

Try something like this :

while (inputFile.hasNext())
{
//Read a number in the file
double number = inputFile.nextDouble();
if (number < lowest) lowest = number;
}

or you could try :

Math.min(lowest, number);

each time in the loop.

OTHER TIPS

First, initialize lowest to positive infinity so that it's larger than any input:

double lowest = Double.POSITIVE_INFINITY;

In the loop, simply take the smaller of lowest and the input:

lowest = Math.min(lowest, number);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top