java – Getting Keyboard Input

java – Getting Keyboard Input

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.

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);
    }
}

java – Getting Keyboard Input

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; //Were going to read all users 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 users 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 wont allow you to do it, or not that easy…

And to validate you use try-catch calls.

Leave a Reply

Your email address will not be published.