Sunday, April 27, 2025

Java Tutorial - User Input - Scanner Class

 This Java code prompts the user to enter an IP address and reads the input from the console.

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner someObj = new Scanner(System.in);
		
		System.out.println("---------------");
		System.out.println("Enter IP: ");
		
		String ip = someObj.nextLine();
		System.out.println("IP: " + ip);
	}	
}

Here are the explanations for each block of code: 

import java.util.Scanner;

This line imports the Scanner class from the java.util package. The Scanner class is used to read input from the user. 

public class Main {

This line begins the definition of the Main class, which is the entry point for the program. 

public static void main(String[] args) {

This line begins the definition of the main method, which is the entry point for the program. The String[] args parameter is used to pass command line arguments to the program. 

Scanner someObj = new Scanner(System.in);

This line creates a new Scanner object called someObj, which is used to read input from the console. 

System.out.println("---------------");
System.out.println("Enter IP: ");

These lines print a message to the console to indicate where the user should enter their input. 

String ip = someObj.nextLine();

This line reads a line of text from the console using the Scanner object and stores it in the ip variable. 

System.out.println("IP: " + ip);

This line prints out the IP address that was entered by the user to the console. The + operator is used to concatenate the string "IP: " with the value of the ip variable.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...