Usage of Scanner

JavaSE provides a class named Scanner in the java.util package, specifically designed for input operations. You can use this class to create an object and then utilize its methods to read data from the keyboard.

Specific implementation steps:

  1. Import the package import java.util.Scanner;
  2. Instantiation of Scanner (creating an object of the class)
  3. Use the Scanner’s next() method to obtain input content of a specified type
    • Scanner does not have a specific next() method for obtaining char type data. However, it provides next() and nextLine() for obtaining strings. If you want to obtain character data, you can first get a string and then perform character extraction operations on the string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Scanner scan = new Scanner(System.in);

// Get string
System.out.println("Please enter your name:");
String name = scan.next();

// Get integer
System.out.println("Please enter your age:");
int age = scan.nextInt();

// Get double precision floating point
System.out.println("Please enter your height (in meters):");
double height = scan.nextDouble();

// Get boolean type
System.out.println("Do you like learning Java:");
boolean isLove = scan.nextBoolean();

System.out.println("Your information is:");
System.out.println("Name:" + name);
System.out.println("Age:" + age);
System.out.println("Height:" + height);
System.out.println("Like Java:" + isLove);

Classic A+B Problem

Input two integers a, b, and output their sum.

1
2
3
4
5
6
7
8
9
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]) throws Exception {
Scanner cin=new Scanner(System.in);
int a = cin.nextInt(), b = cin.nextInt();
System.out.println(a+b);
}
}