User input in java with examples

For Integer:-

import java.util.Scanner;

class group{
public static void main(String arg[]){
int num;
Scanner data = new Scanner(System.in);
System.out.println("Enter a number");
num = data.nextInt();
System.out.println("Entered number is:"+num);
}
}

Above program is simple example for user input where user enter a number which is assigned to variable num.

where Scanner takes information from user keyboard and saved in variable.For using Scanner we have to import Scanner.

Syntax for import a Scanner:-

import java.util.Scanner;

data is Scanner variable. when we press a key, data store value of that key.

num = data.nextInt();
In above line we assigning value of data to num. where num is integer so we used a commend data.nextInt() which Scans input as integer.

Scanner_variable.nextInt(); - The int scanned from the input.

Example:-

Program to find sum of 2 number.

import java.util.Scanner;

class find_sum{
public static void main(String arg[]){
int num1, num2, sum;
Scanner data = new Scanner(System.in);
System.out.println("Enter 1st number");
num1 = data.nextInt();
System.out.println("Enter 2nd number");
num2 = data.nextInt();
sum=num1+num2;
System.out.println("sum of 2 number:"+sum);
}
}

Here data is Scanner variable. int is scanned from input and assigned to num1 and num2 variables.

For Floating Point:-

Scanner_variable.nextFloat(); - The float scanned from the input


Scanner_variable.nextDouble(); - The double scanned from the input.

Example:-

Program to find sum of 2 number.

import java.util.Scanner;

class Find_sum{
public static void main(String arg[]){
double num1, num2, sum;
Scanner data = new Scanner(System.in);
System.out.println("Enter 1st number");
num1 = data.nextDouble();
System.out.println("Enter 2nd number");
num2 = data.nextDouble();
sum=num1+num2;
System.out.println("sum of 2 number:"+sum);
}
}


For Boolean:-

Scanner_variable.nextBoolean(); - The boolean scanned from the input

For Characters:-

Scanner_variable.nextLine(); - The character Scanned from the input.

Example:-

Program to display user input.

import java.util.Scanner;

class disp{
public static void main(String arg[]){
Scanner data = new Scanner(System.in);
System.out.println(data.nextLine());
}
}

or


import java.util.Scanner;

class group{
public static void main(String arg[]){
System.out.println("Enter your text");
Scanner data = new Scanner(System.in);
String text = data.nextLine();
System.out.println(text);
}
}


Previous Code:-
User output

List Code:-
Java codes

Next Code:-
Arithmetic operators

Java Programs:-
List of Java Programs

Leave reply

Add your comments here

Back to Top