Aud
Aud

Reputation: 5

how do I find the smallest number in a text file? (Java)

I have written code for a program meant to have the user input a text file and an output file, then the program must read each line in the input file to find the smallest number. The output is supposed to have the smallest number followed by "<== smallest number". When I run it the smallest number ends up being the last number in the text file every time

This is the code I have so far:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class FindSmallest {

public static void main(String[] args) throws FileNotFoundException {
    Scanner console = new Scanner(System.in);
    System.out.print("Your input file: ");
    String inputFileName = console.next();
    System.out.print("Your output file: ");
    String outputFileName = console.next();


    File inputFile = new File(inputFileName);
    Scanner in = new Scanner(inputFile);
    PrintWriter out = new PrintWriter(outputFileName);

    double smallNum = in.nextDouble();

    while(in.hasNextDouble()){

        double number = in.nextDouble();
        if (number < smallNum); {
            smallNum = number;
        }
    }

    System.out.println(smallNum);
    //out.printf("%8.2f <== smallest number", smallNum);
   in.close(); 
   out.close();
  }

}

Upvotes: 0

Views: 1810

Answers (2)

Alex
Alex

Reputation: 1

You can also use import java.io.; instead of importing specific libraries to shorten your code. "" calls up all the libraries in the specified import.

Upvotes: 0

stackguy
stackguy

Reputation: 190

You have a typo, remove the ';' right after the if (number < smallNum). The ; after the if causes the `smallNum = number;' instruction to run irrespective of the condition.

Upvotes: 2

Related Questions