SoFunction
Updated on 2025-03-08

Simple example of Scanner usage in Java

ScannerIt can realize the interaction between programs and people, and users can use the keyboard to input.

Different types of input:

String s=();  //Accept string data(s);

int s1= ();//Receive integer data(s1);

double s2= ();// Accept decimal data(s2);

For example: enter hello world from the keyboard.

import ;   //Import the package firstpublic class test {
    public static void main(String[] args) {
        //Create a scanner object to receive keyboard data        Scanner  sc=new Scanner();
        //Receive data from the keyboard        String s=();  //Accept string data        (s);
    }
}

hello world
hello

The reason why the above only outputs "hello" is because this input stops accepting when encountering spaces, tabs, or carriage return. Therefore, the data after "hello" will not be accepted. If we want to accept the complete "hello world", we can usenextline()Come and accept it.

nextline()It accepts a line, can accept spaces and tab characters, and will stop accepting data only when the carriage returns are encountered.

import ;   //Import the package firstpublic class test {
    public static void main(String[] args) {
        //Create a scanner object to receive keyboard data        Scanner  sc=new Scanner();
        //Receive data from the keyboard        String s= ();  //Accept string data        (s);
    }
}

hello world
hello world

Example [Guess the Number]

Create the ScannerDemo class, first create a random number in the main method, and then create a while loop to continuously obtain the numbers entered by the user, let the numbers entered by the user compare with the random number, give a prompt of "greater than" or "less than". The loop will not end until the number entered by the user is equal to the random number.

import ;
import ;
 
public class ScannerDemo {
	public static void main(String[] args) {
		Random r = new Random();
		int num = (100);
		int input = -1;
		Scanner scanner = new Scanner();
		while(true) {
			("Guess what is the random number?");
			input=();
			if (input>num) {
				("The number you entered is too big!");
			}else if(input<num) {
				("The number you entered is small!");
			}else if(input==num) {
				break;
			}else {
				("Your input is wrong!");
			}
		}
		("Congratulations on your answer right!");
		();
	}
}

Summarize

This is the end of this article about a simple example of Scanner usage in Java. For more related content on Java Scanner usage, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!