Java Program to Take Input From User - The Coding Shala
Hey there, welcome back to another post. In this post, we are going to learn how to take inputs from the user in Java.
Java Program to Take Input From User
Here, we are going to use the Scanner class to take user input. We will use the below methods:
- For integer: nextInt()
- For long: nextLong()
- For float: nextFloat()
- for double: nextDouble()
- for String: next()
- for complete line: nextLine()
Java Program:
import java.util.Scanner; /** * https://www.thecodingshala.com/ */ public class Main { public static void main(String[] args) { // using Scanner class Scanner sc = new Scanner(System.in); // taking integer inputs // for integers use nextInt() // for long use nextLong() System.out.println("Enter integer"); int num1 = sc.nextInt(); System.out.println("Entered integer is: " + num1); // taking float/Double input // for float -> nextFloat() // for double -> nextDouble() System.out.println("Enter float"); float num2 = sc.nextFloat(); System.out.println("Entered float is: " + num2); // taking string input using next() System.out.println("Enter a string"); String str = sc.next(); System.out.println("Entered string is: " + str); // taking complete line as string input using nextLine() // it will move the cursor to the next line System.out.println("Enter a string with spaces in between"); // String str2 = sc.next(); -> this will take only first word sc.nextLine(); // this will move current cursor to the starting of next line String str2 = sc.nextLine(); System.out.println("Entered string is: " + str2); } }
Output:
Enter integer 5 Entered integer is: 5 Enter float 3.5 Entered float is: 3.5 Enter a string Akshay Entered string is: Akshay Enter a string with spaces in between Hello Akshay, How are you? Entered string is: Hello Akshay, How are you?
Other Posts You May Like
- How to Take Array Input in Java
- How to Take 2D Array Input in Java
- Java Program to Left Rotate an Array
- Java Program to Find the Frequency of Characters in a String
- Java Program to Check Prime Number
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.
Comments
Post a Comment