There are several ways to get input from the user. Here in this program we will take Scanner Class to achieve the task.
This Scanner class comes under java.util, hence the first line of the program is import java.util.Scanner; which allows the user to read values of various types in java. The import statement line should have to be in the first line the java program, and we proceed further for code.
To access methods in Scanner class create a new scanner object as "in". Now we use a one of its method that is "next". "next" method gets the string of text that a user enters on the keyboard.
Depending upon your need use this method :
in.nextInt();
Note : It just reads the numbers, Not the end of line or anything after the number.
Here I'm using in.nextLine(); to get the String which user enters.
This Scanner class comes under java.util, hence the first line of the program is import java.util.Scanner; which allows the user to read values of various types in java. The import statement line should have to be in the first line the java program, and we proceed further for code.
To access methods in Scanner class create a new scanner object as "in". Now we use a one of its method that is "next". "next" method gets the string of text that a user enters on the keyboard.
Depending upon your need use this method :
in.nextInt();
Note : It just reads the numbers, Not the end of line or anything after the number.
Here I'm using in.nextLine(); to get the String which user enters.
import java.util.Scanner; class GetInputFromUser { public static void main(String args[]) { int a; float b; String s; Scanner in = new Scanner(System.in); System.out.println("Enter a string"); s = in.nextLine(); System.out.println("You entered string "+s); System.out.println("Enter an integer"); a = in.nextInt(); System.out.println("You entered integer "+a); System.out.println("Enter a float"); b = in.nextFloat(); System.out.println("You entered float "+b); } }
helpful thnx
ReplyDeleteThank you for this fantastic post bro
ReplyDeleteNice, thank you
ReplyDeletebut how to read Byte or short or character
it is helpful but can you please list other input methods like, BufferedReader,console.
ReplyDelete🍻thanks.
Sure, I will post those too. Thank you for suggesting here.
Deletevery well done, thanks bro.
ReplyDeletethanks it is helpful
ReplyDelete