Getting Keyboard Input
Solution 1
You can use Scanner class
Import first :
import java.util.Scanner;
Then you use like this.
Scanner keyboard = new Scanner(System.in);
System.out.println("enter an integer");
int myint = keyboard.nextInt();
Side note : If you are using nextInt()
with nextLine()
you probably could have some trouble cause nextInt()
does not read the last newline character of input and so nextLine()
then is not gonna to be executed with desired behaviour. Read more in how to solve it in this previous question Skipping nextLine using nextInt.
Solution 2
You can use Scanner class like this:
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner scan= new Scanner(System.in);
//For string
String text= scan.nextLine();
System.out.println(text);
//for int
int num= scan.nextInt();
System.out.println(num);
}
}
Solution 3
You can also make it with BufferedReader if you want to validate user input, like this:
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Areas {
public static void main(String args[]){
float PI = 3.1416f;
int r=0;
String rad; //We're going to read all user's text into a String and we try to convert it later
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Here you declare your BufferedReader object and instance it.
System.out.println("Radius?");
try{
rad = br.readLine(); //We read from user's input
r = Integer.parseInt(rad); //We validate if "rad" is an integer (if so we skip catch call and continue on the next line, otherwise, we go to it (catch call))
System.out.println("Circle area is: " + PI*r*r + " Perimeter: " +PI*2*r); //If all was right, we print this
}
catch(Exception e){
System.out.println("Write an integer number"); //This is what user will see if he/she write other thing that is not an integer
Areas a = new Areas(); //We call this class again, so user can try it again
//You can also print exception in case you want to see it as follows:
// e.printStackTrace();
}
}
}
Because Scanner class won't allow you to do it, or not that easy...
And to validate you use "try-catch" calls.
Solution 4
You can use Scanner class
To Read from Keyboard (Standard Input) You can use Scanner is a class in java.util
package.
Scanner
package used for obtaining the input of the primitive types like int, double
etc. and strings
. It is the easiest way to read input in a Java program, though not very efficient.
- To create an
object
ofScanner
class, we usually pass the predefined objectSystem.in
, which represents the standard input stream (Keyboard).
For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
Some Public methods in Scanner
class.
-
hasNext()
Returns true if this scanner has another token in its input. -
nextInt()
Scans the next token of the input as an int. -
nextFloat()
Scans the next token of the input as a float. -
nextLine()
Advances this scanner past the current line and returns the input that was skipped. -
nextDouble()
Scans the next token of the input as a double. -
close()
Closes this scanner.
For more details of Public methods in Scanner class.
Example:-
import java.util.Scanner; //importing class
class ScannerTest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in); // Scanner object
System.out.println("Enter your rollno");
int rollno = sc.nextInt();
System.out.println("Enter your name");
String name = sc.next();
System.out.println("Enter your fee");
double fee = sc.nextDouble();
System.out.println("Rollno:" + rollno + " name:" + name + " fee:" + fee);
sc.close(); // closing object
}
}
Solution 5
You can use Scanner to get the next line and do whatever you need to do with the line entered. You can also use JOptionPane to popup a dialog asking for inputs.
Scanner example:
Scanner input = new Scanner(System.in);
System.out.print("Enter something > ");
String inputString = input.nextLine();
System.out.print("You entered : ");
System.out.println(inputString);
JOptionPane example:
String input = JOptionPane.showInputDialog(null,
"Enter some text:");
JOptionPane.showMessageDialog(null,"You entered "+ input);
You will need these imports:
import java.util.Scanner;
import javax.swing.JOptionPane;
A complete Java class of the above
import java.util.Scanner;
import javax.swing.JOptionPane;
public class GetInputs{
public static void main(String args[]){
//Scanner example
Scanner input = new Scanner(System.in);
System.out.print("Enter something > ");
String inputString = input.nextLine();
System.out.print("You entered : ");
System.out.println(inputString);
//JOptionPane example
String input = JOptionPane.showInputDialog(null,
"Enter some text:");
JOptionPane.showMessageDialog(null,"You entered "+ input);
}
}
Related videos on Youtube
user1342573
Updated on July 09, 2022Comments
-
user1342573 almost 2 years
How do I get simple keyboard input (an integer) from the user in the console in Java? I accomplished this using the
java.io.*
stuff, but it says it is deprecated.How should I do it now?
-
user207421 almost 4 yearsBe specific. The '
java.io.*
stuff' isn't deprecated. OnlyDataInputStream.readLine()
. There is stillBufferedReader.readLine()
, as well as the other suggestions you've been given here.
-
-
user1342573 almost 11 yearsIt says cannot find symbol Scanner
-
nachokk almost 11 years@user1342573 you have to import
java.util.Scanner
-
Dummy Code almost 11 years@nachokk I actually typed it up while you posted yours. My bad.
-
Raffi Khatchadourian about 9 yearsYou can call
nextInt()
instead ofnextLine()
. -
most venerable sir about 9 yearsIs "in" keyboard in Java and "out" screen?
-
nachokk about 9 years@Doeser they are class members variables (static) defined in System class,
-
most venerable sir about 9 yearsWhy you use keyboard instead of in?
-
samsamara over 7 yearsI don't understand why you say "Because Scanner class won't allow you to do it, or not that easy..."? IMO you can?
-
samsamara over 7 yearsAlso if you wanna call that class again (or to continue execution) you should call "a.main(null)" after instantiating, or just do "Areas.main(null)"
-
Frakcool over 7 years@KillBill thanks for your comment, I had forgotten about this question, in a few days I'll try to edit it with a better explanation, when I wrote this answer I was starting my high school studies, today I work in an IT company and I'll write this in the best way I can; back then I was a complete newbie, I can't edit it right now because I have some work to do, but I promise I'll edit and let you know.
-
Frakcool over 7 years@KillBill Thanks for that method about
Areas.main(null)
but in that case if you want to reuse the code, you should place it inside a method, the code in my answer was made on the main method because I tried to make a minimal reproducible example so anyone who came up my answer could easily copy-paste it and see what it does w/o extra work -
samsamara over 7 years@Frakcool What i wanted to say is your code as is doesn't continue execution. Anyways no worries mate..as your wish
-
Mojtaba about 5 years@mostvenerablesir it's a variable dude!
-
user207421 almost 4 yearsYou still need to fix this.
Scanner
can do all this, and without thetry-catch
structure: and if you're going to usetry-catch
you should at least catch the specificNumberFormatException
, not justException
.