Java - 我无法让用户关闭程序

时间:2017-10-28 19:56:26

标签: java user-input

问题出在第43行。我正在尝试询问用户是否要通过键入Y / N来退出程序,如果用户键入Y则程序应该关闭。但是,我已经尝试了所有我知道的东西,我无法理解。我试着问我的教授,但是他告诉我使用.equals()方法,然后离开房间,然后才能问他更多。整个程序做了它应该做的事情,除了那个给我最多问题的功能,即用户输入内容。

    // 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.");
   }
   }

1 个答案:

答案 0 :(得分:1)

看起来问题在于:

if(filename .equals(Y))

不要为Y创建变量。只需在此输入一个字符串即可。 它看起来应该如何:

if(filename.equalsIgnoreCase("Y")) // Used ignorecase to accept small y

这会解决您的问题吗?