This tutorial is a little more advanced. To use this with a scanner, you have to use also a new part of the theory. I will give a short explanation about it:
First I will show you how to use it then add the last part of this page/article I will explain the “new part”, that is the try and catch statement.
Alright, to get input from a file, you first have to import:
- class scanner
- class File
- We use this as a tool to give the content of the file to the scanner.
Oke,
You will give everything in your file to your scanner, therefore you need to use the Class File. First, save everything of the file in the class File. This is the way to do this:
- So you name your file: “file”, and give as input the location(User/username/Downloads/) and the name of the file (hoi.txt)
Now you can give this variable “file” to your scanner
We will get an exception at this point because as you should see will your program give an error, and when you click on it you see two options: “add throws declaration” or “surround with try/catch”.
Try and catch
In short, both options will do more or less the same thing. It tries your commands in the method and if there is an error the program catches the error. You will use this when you:
- don’t want your program to crash
- when you want your program to crash but want to control which error the program gives as output
For now, it is not really important. I will give three options for now:
- just print the standard error
add after every method: throws FileNotFoundException
2. print a personalised error
3. print an error but don’t let the program crash
This is a bigger program as the programs of example 1 and 2. Now you could see that if you give a wrong file as input the rest of the program will still continue.