How to Use Scanner in Java?

Import the Scanner class: `import java.util.Scanner;`

Create a Scanner object: `Scanner sc = new Scanner(System.in);`

Read a string: `String text = sc.nextLine();`

Read a single word: `String word = sc.next();`

Read an integer: `int num = sc.nextInt();`

Read a double: `double value = sc.nextDouble();`

Read a float: `float f = sc.nextFloat();`

Read a long: `long l = sc.nextLong();`

Read a boolean: `boolean flag = sc.nextBoolean();`

Read a short: `short s = sc.nextShort();`

Read a byte: `byte b = sc.nextByte();`

Read a char: `char ch = sc.next().charAt(0);`

Check for more input: `sc.hasNext()`

Check for more integer input: `sc.hasNextInt()`

Check for more double input: `sc.hasNextDouble()`

Check for more line input: `sc.hasNextLine()`

Close the Scanner when done: `sc.close();`

Use `nextLine()` after numeric input carefully to consume leftover newline

Use `useDelimiter()` to change input separator if needed

Use `skip()` to ignore unwanted input patterns

Use `hasNextX()` before reading to avoid input errors

Suggested for You

Trending Today