Java Scanner Quick Guide for Exam
Scanner with File Reading, try-catch, and .hasNextLine()
import [Link];
import [Link];
import [Link];
public class ReadFileExample {
public static void main(String[] args) {
try {
File myFile = new File("[Link]"); // Replace with your file name
Scanner sc = new Scanner(myFile); // Create Scanner to read file
// Read all lines using hasNextLine
while ([Link]()) {
String line = [Link]();
[Link]("Line: " + line);
}
[Link](); // Always close the scanner
} catch (FileNotFoundException e) {
[Link]("File not found!");
[Link](); // Prints the error for debugging (optional)
}
}
}
Explanation
- File myFile = new File(...) -> Points to the file you want to read
- Scanner sc = new Scanner(...) -> Reads from the file instead of the keyboard
- while ([Link]()) -> Reads all lines until the file ends
- try { ... } catch { ... } -> Catches errors like missing file
- FileNotFoundException -> Specific error when file is not found
Make sure:
- You have a file named [Link] in the project folder.
- Or change "[Link]" to the path of your real file.
Scanner with try-catch for Keyboard Input
import [Link];
import [Link];
public class ScannerInputExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try {
[Link]("Enter an integer: ");
int number = [Link](); // Reads an int
[Link]("Enter a decimal: ");
double decimal = [Link](); // Reads a double
[Link](); // Clear newline
[Link]("Enter a word: ");
String word = [Link](); // Reads a word
[Link](); // Clear newline
[Link]("Enter a full line: ");
String line = [Link](); // Reads a full line
[Link]("Inputs: " + number + ", " + decimal + ", " + word + ", " + line);
} catch (InputMismatchException e) {
[Link]("Invalid input! Please enter correct data types.");
} finally {
[Link](); // Always close scanner
}
}
}