Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Keyboard Input

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?

like image 575
user1342573 Avatar asked Jul 09 '13 00:07

user1342573


People also ask

How do I get keyboard input in python?

Use the input() function to get Python user input from keyboard. Press the enter key after entering the value. The program waits for user input indefinetly, there is no timeout.


2 Answers

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.

like image 135
nachokk Avatar answered Sep 16 '22 13:09

nachokk


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);     } } 
like image 34
Mike B Avatar answered Sep 17 '22 13:09

Mike B