FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

Get input from user


In this tutorial we are gonna see how to accept input from user. We are using Scanner class to get the input. In the below example we are getting input String, integer and a float number. For this we are using following methods:

1) public String nextLine(): For getting input String

2) public int nextInt(): For integer input

3) public float nextFloat(): For float input

import java.util.Scanner;

class GetInputData
{
  public static void main(String args[])
  {
     int num;
     float fnum;
     String str;
 
     Scanner in = new Scanner(System.in);
 
     //Get input String
     System.out.println("Enter a string: ");
     str = in.nextLine();
     System.out.println("Input String is: "+str);
 
     //Get input Integer
     System.out.println("Enter an integer: ");
     num = in.nextInt();
     System.out.println("Input Integer is: "+num);
 
     //Get input float number
     System.out.println("Enter a float number: ");
     fnum = in.nextFloat();
     System.out.println("Input Float number is: "+fnum); 
  }
}

Output

Enter a string: 
apple
Input String is: apple
Enter an integer: 
27
Input Integer is: 27
Enter a float number: 
12.56
Input Float number is: 12.56

You may also Find this interesting

Program to take users input

Program to add two numbers

Program to find even number

Program to find odd numbers

Program to find even or odd numbers

Program to Display average of numbers

Program to Display Fabinocci Series

Program to Display Random Numbers

Program to Display Largest of Three numbers