lundi 21 septembre 2015

Java: Trying to create a file input program. But, user must input correct file name or it wont open

import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Workshop5
{
   public static void main(String[] args)
{
  Scanner keyboard = new Scanner(System.in); // Prompting Scanner -> keyboard
  String file;
  System.out.println("Hello, this program will be used to help determine miles per gallon used.");
  System.out.print("Please input file name here: ");
  file = keyboard.nextLine();
  Scanner fileIn = null ; // initializes fileIn to empty
  try
  {
  // Attempting to open your file.
     fileIn = new Scanner( new FileInputStream("MilesPerGallon.txt"));
  }
  catch (FileNotFoundException e)
  {
     System.out.println("File not found.");
     System.exit(0);
  }
  String name;
  double gasUsed;
  int milesDriven;
  name = fileIn.nextLine();
  gasUsed = fileIn.nextDouble();
  milesDriven = fileIn.nextInt();
  double milesPerGallon = (milesDriven/gasUsed);
  System.out.println(name + " drove " + milesDriven + " miles the other day, using a total of " + gasUsed + " gallons of gas.");
  fileIn.close();
  System.out.printf("Total number of Miles per Gallon: " + "%2.2f", milesPerGallon);
       }
   }

This is what i have. I have a file, names MilesPerGallon.txt. If i type in kashdkjashgkhjfgk it still opens the file MilesPerGallon.txt. Anyone know how I can create an if statement or something to make it to where the keyboard entered text for the file name MUST = MilesPerGallon.txt? Please help!

Aucun commentaire:

Enregistrer un commentaire