Getting Keyboard Input

569,767

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.

  1. To create an object of Scanner class, we usually pass the predefined object System.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);
    }
}
Share:
569,767

Related videos on Youtube

user1342573
Author by

user1342573

Updated on July 09, 2022

Comments

  • user1342573
    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
      user207421 almost 4 years
      Be specific. The 'java.io.* stuff' isn't deprecated. Only DataInputStream.readLine(). There is still BufferedReader.readLine(), as well as the other suggestions you've been given here.
  • user1342573
    user1342573 almost 11 years
    It says cannot find symbol Scanner
  • nachokk
    nachokk almost 11 years
    @user1342573 you have to import java.util.Scanner
  • Dummy Code
    Dummy Code almost 11 years
    @nachokk I actually typed it up while you posted yours. My bad.
  • Raffi Khatchadourian
    Raffi Khatchadourian about 9 years
    You can call nextInt() instead of nextLine().
  • most venerable sir
    most venerable sir about 9 years
    Is "in" keyboard in Java and "out" screen?
  • nachokk
    nachokk about 9 years
    @Doeser they are class members variables (static) defined in System class,
  • most venerable sir
    most venerable sir about 9 years
    Why you use keyboard instead of in?
  • samsamara
    samsamara over 7 years
    I don't understand why you say "Because Scanner class won't allow you to do it, or not that easy..."? IMO you can?
  • samsamara
    samsamara over 7 years
    Also 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
    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
    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
    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
    Mojtaba about 5 years
    @mostvenerablesir it's a variable dude!
  • user207421
    user207421 almost 4 years
    You still need to fix this. Scanner can do all this, and without the try-catch structure: and if you're going to use try-catch you should at least catch the specific NumberFormatException, not just Exception.