Java – User Input

To get input from a user in Java, use the Scanner class. The java.util package has the Scanner class. First, import the Scanner:

import java.util.Scanner;

Read a string value from the user in Java

To read the strings, we have used the nextLine() method. Let us see an example wherein we are asking the user to enter the country name:

import java.util.Scanner;

class Studyopedia {
  public static void main(String[] args) {
    Scanner ob = new Scanner(System.in);
    String country;
    
    // User enters the country name and enter is pressed
    System.out.println("Enter your Country:"); 
    country = ob.nextLine();   
       
    System.out.println("Country = " + country);        
  }
}

Output

Enter your Country:
India
Country = India

Read a boolean value from the user in Java

To read a boolean value, we have used the nextBoolean() method. Let us see an example wherein we are asking the user to enter the True or False values for the result:

import java.util.Scanner;

public class Studyopedia {
  public static void main(String[] args) {
     System.out.print("Did you pass the exam?");  
     Scanner ob = new Scanner(System.in);  
     
     boolean b = ob.nextBoolean();  
     
     if (b == true) {  
       System.out.println("Yes, you passed the exam.");  
     } else if (b == false) {  
       System.out.println("No, you failed the exam.");  
     }    
  }
}

Output

Did you pass the exam?
True
Yes, you passed the exam.

Read a double value from the user in Java

To read a double value, we have used the nextDouble() method. Let us see an example wherein we are asking the user to enter the points:

import java.util.Scanner;

public class Studyopedia {
  public static void main(String[] args) {
    Scanner ob = new Scanner(System.in);
    double points;
    
    // User enters the points and enter is pressed
    System.out.println("Enter the Player Points:"); 
    points = ob.nextDouble();   
       
    System.out.println("Points = " + points);        
  }
}

Output

Enter the Player Points:
122.5
Points = 122.5

Read an int value from the user in Java

To read an integer value, we have used the nextInt() method. Let us see an example wherein we are asking the user to enter the marks:

import java.util.Scanner;

public class Studyopedia {
  public static void main(String[] args) {
    Scanner ob = new Scanner(System.in);
    int marks;
    
    // User enters the marks and enter is pressed
    System.out.println("Enter your Marks:"); 
    marks = ob.nextInt();   
       
    System.out.println("Marks = " + marks);        
  }
}

Output

Enter your Marks:
95
Marks = 95

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Java Exception Handling
Java Regular Expressions
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment