Help writing some Scanner code
Hi.
I'm writing a program that will do different sort of things to matrices (add, subtract, multiply) from a file. I'd like to ask the user which file they would like read, and then read the file for the matrices.
How do I create a scanner object that will user input files to do that?
Re: Help writing some Scanner code
Code :
new Scanner(new File(new Scanner(System.in).nextLine()));
Re: Help writing some Scanner code
Ok, I have that, but now I'd like to surround it by a try/catch phrase in case the user puts in a file that isn't recognized or can't be read.
I know that I have to exit the program and return a negative value at some point, I'm just not sure where. Here's what I have:
Code :
public static void askForFileName() {
System.out.println("Please enter a file name ==> ");
try {
new Scanner(new File(new Scanner(System.in).nextLine()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Also, if I create a method that will read the file entered by the user here, should I give it a variable in this method and call it in the read method, or what would be the best way to go about that?
Re: Help writing some Scanner code
You are asking questions which contradict each other. You first asked how to open a file to be read based on user input. The you place it in a method called askForFileName() so all it should do is ask for a file name, not try to open it! You need to re-think how you are coding this, remember java is OOP and if this is an assignment, the previous line of code I gave you will give you next to no marks due to its poor presentation and readibility.
Regards,
Chris
Re: Help writing some Scanner code