19 Jan 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:
1 2 3 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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
1 2 3 4 5 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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
1 2 3 4 5 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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
1 2 3 4 5 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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
1 2 3 4 5 |
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
No Comments