String Input
-
import java.util.Scanner;
: The Scanner class is a part of Java’s standard library and is used for reading input from various sources, such as the keyboard (standard input). -
public class UserInput {
: Define the UserInput class. In Java, all codes must be a contained within a class, and the class name must be match the filename (UserInput.java) -
public static void main (String[] args) {
: main method, The main method is the entry point for any Java application. -
Scanner scanner = new Scanner(System.in);
: The Scanner is set to read input from System.in, which represents standard input (typically the keyboard). -
String name = scanner.nextLine();
: The nextLine() method of the Scanner object reads the entire line of input that the user enters, This input is stored in the String variablename
,The nextLine() method reads everything the user types until they press the Enter key, making it ideal for capturing full lines of text.
Int Input
What if we input string to age
variable? that leads to Exception Error
saying Exception in thread "main" java.util.InputMismatchException
. We will cover Exception Handling later
Common issue happens after we use nextInt() after nextLine()
What happens here is after we enter our age. input for favourite is going to skip by java. like this :
What happens here is :
What happens when u use nextLine()
:
Transclude of User-input-(Scanner)-2024-08-30-00.39.07.excalidraw
But what happens when u use nextInt()
:
Transclude of User-input-(Scanner)-2024-08-30-00.46.44.excalidraw
FIX 💡
To get rid of this we can place empty
scanner.nextLine()
method afternextInt()
to clear out the scanner