Lecture1c- Scanner Flashcards
What is System.in in Java?
A standard input stream used to read input from the console.
An instance of InputStream, automatically instantiated by Java.
Typically wrapped by a Scanner object for easier input handling.
What is the Scanner class in Java?
A text parser that reads numbers, words, or phrases from an input source.
Helps create interactive programs.
Defined in java.util.Scanner and must be imported.
How do you create a Scanner object?
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
What are some common Scanner methods?
next() → Reads next token as a String
nextLine() → Reads entire line as a String
nextInt() → Reads an int
nextDouble() → Reads a double
hasNext() → Checks if another token exists
How do you read different data types using Scanner?
int num = scan.nextInt();
double decimal = scan.nextDouble();
String word = scan.next();
String line = scan.nextLine();
What are some useful Scanner validation methods?
hasNext() → Checks if there is another token.
hasNextLine() → Checks if another line exists.
hasNextInt() → Checks if the next token is an int.
hasNextDouble() → Checks if the next token is a double.
What is the difference between print() and println()?
print() → Prints output but stays on the same line.
println() → Prints output and moves to the next line.
What does this Java program do?
import java.util.Scanner;
public class TestScanner {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print(“Enter a number: “);
double value = scan.nextDouble();
System.out.println(“Entered “ + value);
}
}
Prompts the user to enter a number.
Reads the number as a double.
Displays the entered number.
What is an example of using nextLine()?
Scanner scan = new Scanner(System.in);
System.out.println(“Enter a sentence:”);
String message = scan.nextLine();
System.out.println(“You entered: “ + message);