The problem is on line 43. I'm trying to ask the User if they want to quit the program by typing Y/N if the User types Y then the program should close. However, I've tried everything I know and I can't figure it out. I tried to ask my professor but he told me to use the .equals() method then left the room before I could ask him more about it. The entire program does what it's supposed to do except for the one feature that's giving me the most problems which is the user input stuff.
// The goal of this program is to . . .
// Get the name of a file from the user
// Check if the file is valid (Try Catch) and intercept a
// FileNotFoundException
// If this happens the program should prompt the user to either try to
// enter the name of a file again
// Or terminate the program if they feel lazy
// If the file is valid then the program should change the data in the
// specified folder
// Or prompt the user to enter a valid name again or terminate the
//program
import java.util.Scanner;
import java.io.*;
public class FileSum {
public static void main(String[] args) throws IOException
{
double sum = 0.0;
Boolean i = null;
String Y = null;
// Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
// Get the name of the file
System.out.print("Enter the filename: ");
String filename = keyboard.nextLine();
// Do While loop will make sure that the User can get as many tries as they need to input a correct
do{
try
{
// Open the File
File file = new File(filename);
Scanner inputFile = new Scanner(file);
i = true;
}
catch (FileNotFoundException e)
{
i = false; // This will make the program repeat here
System.out.println("Can't find the file. Please enter a new filename (Press Y to quit): ");
filename = keyboard.nextLine();
if(filename .equals(Y)) { // This is supposed to make the application end. This is the part that I can't figure out what's wrong
System.out.println("You have ended the program.");
System.exit(0);
}
}
}while(i == false); // When (i == false) the loop will continue
// Open the File
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Read all values from the file and compute total
while (inputFile.hasNext())
{
double number = inputFile.nextDouble();
sum = sum + number;
}
inputFile.close(); // Close the file.
System.out.println("Sum of numbers is " + sum);
System.out.println("End of the program.");
}
}
Looks like the problem is with this:
if(filename .equals(Y))
Don't make a variable for Y. Just type here a string. How it probably should look:
if(filename.equalsIgnoreCase("Y")) // Used ignorecase to accept small y
Does this solve your problem?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.