I was trying to write code which would read an input file and create an output file. But when I tried to add a try until a correct input file name is input, I had problems. It shows not proper filenotfound exception is in try....
public static void main(String[] args) throws FileNotFoundException
{
//prompt for the input file name
Scanner in = new Scanner(System.in);
//keep trying until there are no more exceptions
//boolean done = false;
String inputfilename = " ";
while (!done)
{
try
{
System.out.print("Input file name (from your computer): ");
inputfilename = in.next();
done = true;
}
catch (FileNotFoundException exception)
{
System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again.");
}
}
//prompt for the output file name
System.out.print("What would you like to call your output file: ");
//use outputfilename variable to hold input value;
String outputfilename = in.next();
//construct the Scanner and PrintWriter objects for reading and writing
File inputfile = new File(inputfilename);
Scanner infile = new Scanner(inputfile);
PrintWriter out = new PrintWriter(outputfilename);
//read the input and write the output
out.println("Here is the class average for mstu4031:\n");
double totalgrade = 0;
double number = 0;
while (infile.hasNextDouble())
{
double grade = infile.nextDouble();
out.println("\n");
out.printf("%.1f\n",grade);
number++;
totalgrade = totalgrade + grade;
}
//print numbers and average in output file
out.println("\n\n");
out.printf("\nNumber of grades: %.1f",number);
//calculate average
double average = totalgrade/number;
out.println("\n\n");
out.printf("\nAverage: %.2f",average);
finally
{
in.close();
out.close();
}
}
There is no method in your try block that may throw a FileNotFoundException.
Try to instantiate your Scanner in the try block. It will throw the expected FileNotFoundException if the filename read from stdin does not exist:
String inputfilename = null;
Scanner infile = null;
while (!done)
{
try
{
System.out.print("Input file name (from your computer): ");
inputfilename = in.next();
infile = new Scanner(new File(inputfilename));
done = true;
}
catch (FileNotFoundException exception)
{
System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again.");
}
}
Wrong here. You are only receiving input without checking if the file actually exist. Every valid inputs will let you get out of the loop.
if(new File(inputfilename).exist()){
done = true;
}else{
System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again.");
}
You can only catch an exception if something in the try block may throw an exception.
However, you should test for existence of a file with File.exists(), instead of catching an exception.
File file;
do {
System.out.print("Input file name (from your computer): ");
file = new File(in.next());
} while (!file.exists());
Opening a file may throw an Exception. That's Why you need to put them inside try block. You have put only reading the input part inside try-catch block
Hope this code works properly:
//prompt for the input file name
Scanner in = new Scanner(System.in);
//keep trying until there are no more exceptions
//boolean done = false;
String inputfilename = " ";
while (!done)
{
try
{
System.out.print("Input file name (from your computer): ");
inputfilename = in.next();
done = true;
//prompt for the output file name
System.out.print("What would you like to call your output file: ");
//use outputfilename variable to hold input value;
String outputfilename = in.next();
//construct the Scanner and PrintWriter objects for reading and writing
File inputfile = new File(inputfilename);
Scanner infile = new Scanner(inputfile);
PrintWriter out = new PrintWriter(outputfilename);
//read the input and write the output
out.println("Here is the class average for mstu4031:\n");
double totalgrade = 0;
double number = 0;
while (infile.hasNextDouble())
{
double grade = infile.nextDouble();
out.println("\n");
out.printf("%.1f\n",grade);
number++;
totalgrade = totalgrade + grade;
}
//print numbers and average in output file
out.println("\n\n");
out.printf("\nNumber of grades: %.1f",number);
//calculate average
double average = totalgrade/number;
out.println("\n\n");
out.printf("\nAverage: %.2f",average);
}
catch (FileNotFoundException exception)
{
System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again.");
}
}
finally
{
in.close();
out.close();
}
Related
I need to put my searching of the file in my readData() method in a loop that catches the fine not found exception then loops to prompt the user again for the file name until the correct one is entered. Once the proper file name is entered, then the return values pass to the other methods to continue the code.
I have tried putting the block of code into a do-while method but it results in a infinite loop. I need assistance with the semantics of this.
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
String inputFileName;
double value;
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the input file: ");
inputFileName = input.nextLine();
File file = new File(inputFileName);
do{
try {
input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
}
catch (FileNotFoundException e) {
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
}
}
while(!file.exists());
return inputValues;
}
I am expecting this to explain "File not found!" then prompt again for the file name until the correct one is entered. However it only does the try-catch once and then attempts to return the inputValues return value. This causes the program to crash.
I have tried do while loop. But it ends up in an infinite loop
package weightedavgdataanalyzer;
import java.io.*;
import java.util.*;
public class WeightedAvgDataAnalyzer {
public static void main(String[] args) {
ArrayList<Double> inputValues = readData();
double weightedAvg = calcWeightedAvg(inputValues);
printResults(inputValues, weightedAvg);
}
private static void printResults(ArrayList<Double> inputValues, double weightedAvg) {
System.out.print("Enter output file name: ");
Scanner input = new Scanner(System.in);
String outputFile = input.nextLine();
try {
PrintWriter writer = new PrintWriter(outputFile);
writer.print("The weighted average of the numbers is " + weightedAvg + ", when using the data ");
for (int i = 2; i < inputValues.size(); i++) {
writer.print(inputValues.get(i) + ", ");
}
writer.println("where " + inputValues.get(0)
+ " is the weight used, and the average is computed after dropping the lowest "
+ Integer.valueOf((int) inputValues.get(1).doubleValue()) + " values.");
writer.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static double calcWeightedAvg(ArrayList<Double> inputValues) {
double sum = 0;
double average;
double weight = inputValues.get(0);
int toDrop = Integer.valueOf((int) inputValues.get(1).doubleValue());
ArrayList<Double> newList = new ArrayList<>();
for (int i = 2; i < inputValues.size(); i++) {
newList.add(inputValues.get(i));
}
Collections.sort(newList);
for (int i = (toDrop); i < newList.size(); i++) {
sum += weight * newList.get(i);
}
average = sum / (newList.size() - toDrop);
return average;
}
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
String inputFileName;
double value;
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the input file: ");
inputFileName = input.nextLine();
File file = new File(inputFileName);
do{
try {
input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
}
catch (FileNotFoundException e) {
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
}
}
while(!file.exists());
return inputValues;
}
}
Move the initialization of File file = new File(inputFileName); inside the loop as well as the "ask for new file name line". And last step is to also check if the file is an directory. You can't read directories with a Scanner, but file.exists() will still return true
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
String inputFileName;
double value;
Scanner input = new Scanner(System.in);
File file;
System.out.print("Enter the name of the input file: ");
do {
inputFileName = input.nextLine();
file = new File(inputFileName);
try {
input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
}
} while (!file.exists() && !file.isDirectory());
return inputValues;
}
The other answers have not addressed that it is bad practice to control the flow of your code using catch and exception. You should reserve using your catch block for typically printing your errors or logging them.
I moved the logic of asking for the file into a loop that does not depend on an exception to correctly execute and placed it into a reusable method.
Here is what this change would look like:
ArrayList<Double> inputValues = new ArrayList<>();
double value;
File file = promptForFile(); //Condensed into a clean reusable single line of code
try {
Scanner input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
} catch (FileNotFoundException e) {
e.printStackTrace(); //Or log the error
}
And the method you can reuse anywhere for a new prompt:
public static File promptForFile()
{
System.out.print("Enter the name of the input file: ");
Scanner input = new Scanner(System.in);
String inputFileName = input.nextLine();
File file = new File(inputFileName);
while(!file.exists() && !file.isDirectory())
{
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
inputFileName = input.nextLine();
file = new File(inputFileName);
}
return file;
}
Now the logic of your code is separated from searching for the file and the code is extremely reusable and readable.
This couldn't be done before since you had two different logics mixed intertwined.
File myFile = new File("myFile.txt");
while(!myFile.exists()){
//re-enter filename and instantiate myFile as a new object using it as the argument
}
could just check whether the file exists in a loop like so before using it. The issue with looping for the FileNotFoundException is that your writer is what throws that, so you would have to constantly instantiate the writer and check whether the exception is thrown before possibly looping again, which isn't ideal.
The problem is when the exception is caught, you never ask for a new file name, so you are running the code on the same faulty file path over and over again. To fix this, just move this code block:
System.out.print("Enter the name of the input file: ");
inputFileName = input.nextLine();
File file = new File(inputFileName);
inside the loop.
You may also want to eliminate a condition on your loop, and instead add a return; at the end of your try block.
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
String inputFileName;
double value;
Scanner input = new Scanner(System.in);
while (true) {
try {
// Get response in the loop, instead of one time-only
System.out.print("Enter the name of the input file: ");
inputFileName = input.nextLine();
File file = new File(inputFileName);
input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
// Add your return statement here to get rid of the conditional
// loop.
return inputValues;
}
catch (FileNotFoundException e) {
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
}
}
}
You can take input and can return once file is found or else can keep recording error message
public File getFile(){
while(true) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter the name of the input file: ");
File file = new File(System.in);
if (file.exists()) {
return file;
}else{
System.out.println("File not found! Please try again ");
}
}
}
}
private List<Double> getData(File file){
List<Double> listOfDoubles = new ArrayList<>();
try(Scanner scanner = new Scanner(file)){
while(scanner.hasNextDouble()) {
listOfDoubles.add(scanner.nextDouble());
}
}
return listOfDoubles;
}
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
File inputFile = getFile();
return getData(inputFile);
}
Hi guys need help for my mini project for schools. How do i compare the user input and match to my database in text file. this is like validity for username and password. I want to call the second line on my data base using account Number and pin.
this is my data base.
0,admin,adminLastName,123456,123456
1,user,userLastName,1234567,123456
0 = id
admin = name
adminLastName = Last Name
1234567 = accountNumber
123456 = pin
and this is my code.
package atm;
import java.io.File;
import java.util.Scanner;
public class Login {
static void verifyLogin(String name, String lastName, String userAccountNumber, String userPin, String filePath){
Scanner inputData = new Scanner(System.in);
boolean isFound = false;
String tempAccountNumber = "";
String tempPin = "";
System.out.print("\nAccount Number: ");
userAccountNumber = inputData.next();
System.out.print("\nPIN: ");
userPin = inputData.next();
try{
Scanner readTextFile = new Scanner(new File("myDataBase.txt")).useDelimiter("[,\n]");
while (readTextFile.hasNext() && !isFound){
tempAccountNumber = readTextFile.next();
tempPin = readTextFile.next();
if (tempAccountNumber.trim().equals(userAccountNumber.trim()) && tempPin.trim().equals(userPin.trim())){
isFound = true;
System.out.println("Welcome " + name+ " " +lastName);
System.out.println("\nLogin Successfully!");
}
else {
System.out.println("You have entered your PIN or ACCOUNT NUMBER incorrectly. Please check your PIN or ACCOUNT NUMBER and try again.\n If you don't have account yet please go to SignUp page!\n");
myMain mainMenu = new myMain();
mainMenu.inputKeyboard();
}
}
readTextFile.close();
}
catch (Exception e){
}
inputData.close();
}
}
If your textfile contains 1 user per line, and you split it with ',' then you can take each line like you do, then split that line into a string[] array and check if i.e. the name corresponds to 'admin'.
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Boolean loggedin = false;
String fileName = "accounts.txt";
String line = null;
System.out.println("What's your username?");
String tempUsername = input.nextLine();
System.out.println("What's your password?");
String tempPassword = input.nextLine();
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
String[] currAccount = line.split(",");
if (currAccount[1].equals(tempUsername) && currAccount[4].equals(tempPassword)) {
loggedin = true;
System.out.println("You have successfully logged in!");
}
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
ex.printStackTrace();
// Let's create it if file can't be found or doesn't exist, but let's ask first.
String answer;
System.out.print("File not found, do you want to create it? [Y/n]: ");
answer = input.nextLine();
if (answer.equalsIgnoreCase("y")) {
try {
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
System.out.println("File has been created!");
} catch (IOException exc) {
exc.printStackTrace();
}
} else {
System.out.println("File was not created!");
}
}
catch(IOException ex) {
ex.printStackTrace();
}
if (!loggedin) {
System.out.println("Your login combination did not exist.");
}
}
}
Please note, I haven't commented a lot, but it should still make sense.
After splitting remember that you start at array index 0, and not 1. So at index 1 the name on the account will be.
Goodluck.
I have a Names.txt file I created with 4 names,bill,dave,mike, andjim
I can enter the file name and I can enter the name to search, for example dave above and then the console should return "dave appears on line 2 of Names.txt". Instead it returns "dave does not exist", which would be correct if it is not one of the four names. What mistake I am making in my while loop below?
public class names {
public static void main(String[] args) throws IOException {
String friendName; // Friend's name
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the filename.
System.out.print("Enter the filename: ");
String filename = keyboard.nextLine();
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Get the name of a friend.
System.out.print("Enter name to search: ");
friendName = keyboard.nextLine().toLowerCase();
int lineNumber = 1;
while (inputFile.hasNextLine()) {
if ("friendName".equals(inputFile.nextLine().trim())) {
// found
String line = inputFile.nextLine();
System.out.println("friendName" + " appears on line " + lineNumber + " of Names.txt");
lineNumber++;
//break;
} else {
// not found
System.out.println(friendName + " does not exist. ");
break;
}
}
// Close the file.
inputFile.close();
}
}
Remove the quotes from friendName and use the actual variable which you read in from the file:
int lineNumber = 1;
booelan found = false;
while (inputFile.hasNextLine()) {
String nextLine = inputFile.nextLine().trim();
if (friendName.equals(nextLine)) {
// found
found = true;
break; // name is found, no point in searching any further
}
lineNumber++; // always increment the line number
}
if (found) {
System.out.println(friendName + " appears on line " + lineNumber + " of Names.txt");
}
else {
System.out.println(friendName + " does not exist. ");
}
I also changed the way you use your Scanner. In your original code, you were calling Scanner.nextLine() twice in the case of a match with the friend name. This would cause the scanner to advance two lines which is not what you want.
package com.stackoverflow;
import java.io.*;
import java.util.*;
public class Names
{
public static void main(String[]args) throws IOException
{
String friendName; // Friend's name
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the filename.
System.out.print("Enter the filename: ");
String filename = keyboard.nextLine();
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Get the name of a friend.
System.out.print("Enter name to search: ");
friendName = keyboard.nextLine().toLowerCase();
int lineNumber = 0;
Boolean isFound = false;
while(inputFile.hasNextLine()){
lineNumber++;
String line = inputFile.nextLine();
if(line.trim().contains(friendName)){
System.out.println(friendName + " appears on line " + lineNumber + " of Names.txt");
}
}
if(!isFound){
System.out.println("given friend name "+friendName+" not exists in the file");
}
// Close the file.
inputFile.close();
} }
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
System.out.println("Hello, this program will be used to help determine miles per gallon used.");
System.out.print("Please input file name here: ");
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!
System.out.println("Hello, this program will be used to help determine miles per gallon used.");
System.out.print("Please input file name here: ");
Scanner keyboard = new Scanner(System.in); // Prompting Scanner -> keyboard
String fileName = keyboard.nextLine();
Scanner fileIn = null ; // initializes fileIn to empty
try
{
// Attempting to open your file.
fileIn = new Scanner( new FileInputStream(fileName));
}
catch (FileNotFoundException e)
{
System.out.println("File not found.. Please enter correct filename");
e.printStackTrace();
System.exit(0);
}
Having an issue here, I need this loop to print new lines of code to a file until but what it does is print 1 line then fails on the second time round,
Can never get it to print to another line, below is code
public class study {
public static void main(String[] args) throws IOException{
BufferedWriter post = null;
File file = new File("text.txt");
if(!file.exists()){
file.createNewFile();
}
boolean promptUser = true;
FileWriter fileWriter = new FileWriter(file);
post = new BufferedWriter(fileWriter);
try {
while(promptUser){
System.out.println("enter age "); //get age
Scanner getage = new Scanner(System.in);
int age= getage.nextInt();
if(age <20 || age>50){ //age range
System.out.println("age must be between 20 and 50");
System.exit(0);
}
System.out.println("enter name "); //get name
Scanner getname = new Scanner(System.in);
String name= getname.nextLine();
System.out.println("enter email "); //get email
Scanner getarea = new Scanner(System.in);
String email= getarea.nextLine();
post.write(age + "\t"); <===== fails here on second run
post.write(name + "\t");
post.write(email + "\t");
post.newLine();
post.close();
System.out.println("enter quit to quit or any key to continue");
Scanner options = new Scanner(System.in);
String option = options.nextLine();
if(option.equalsIgnoreCase("quit")){
System.out.println("goodbye!");
System.exit(0);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
post.write(age + "\t");
post.newLine();
post.write(name + "\t");
post.newLine();
post.write(email + "\t");
post.newLine();
//remove post.close(); from here
Now it may solve Your problem
Replace post.close(); with post.flush(); and you should be fine.
Close the stream when the exit condition is entered.
FIXED IT GUYS
I needed to move the FileWriter line out of the TRY
import java.io.*;
import java.util.*;
public class study {
public static void main(String[] args) throws IOException {
BufferedWriter post = null;
File file = new File("text.txt"); //create file
if (!file.exists())
{
file.createNewFile();
}
boolean promptUser = true;
FileWriter fileWriter = new FileWriter(file);
try {
while (promptUser) {
post = new BufferedWriter(fileWriter);
System.out.println("enter age "); // get age
Scanner getage = new Scanner(System.in);
int age = getage.nextInt();
if (age < 20 || age > 50){ //age range
System.out.println("age must be between 20 and 50");
System.exit(0);
}
System.out.println("enter name "); //get name
Scanner getname = new Scanner(System.in);
String name= getname.nextLine();
System.out.println("enter email "); // get email
Scanner getarea = new Scanner(System.in);
String email= getarea.nextLine();
//send data to file
post.write(age + ";");
post.write(name + ";");
post.write(email + ";");
post.newLine();
post.flush();
System.out.println("enter quit to quit or any key to continue");
Scanner options = new Scanner(System.in);
String option = options.nextLine();
if (option.equalsIgnoreCase("quit")) {
System.out.println("goodbye!");
post.close(); // close file upon quitting
System.exit(0);
}
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}