[英]Not getting the output I'm looking for in program, also having trouble with a user input equaling a string loop
[英]Java - I'm having trouble getting the user to close the program
问题在第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.");
}
}
看起来问题出在这里:
if(filename .equals(Y))
不要为Y设置变量。只需在此处输入字符串即可。 它看起来应该如何:
if(filename.equalsIgnoreCase("Y")) // Used ignorecase to accept small y
这样可以解决您的问题吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.