Input from keyboard

Can anyone please explain how to read an input to a java code from keyboard.Please explain with an example.

Thanks & Regards,

Rashmi

Comments

  • You can get input from keyboard with two methods.

    [b]1nd method (System.in):[/b]
    [code]import java.io.*;
    public class input {
    public static void main(String args[]){
    try{
    System.out.print("What's your name? ");
    DataInputStream in=new DataInputStream(System.in);
    String name = in.readLine();
    System.out.println("Your name is " + name + "!");
    }catch(IOException e){}
    }
    }[/code]
    Compile the code and run it. The program will ask you about your name. Type your name and press Enter key and program will show your name.

    [b]2nd method (arguments):[/b]
    [code]public class args {
    public static void main(String args[]){
    if(args.length == 0) {
    System.out.println("Type your name as: java args John
    or java args "John Doe"");
    }
    else {
    System.out.println("Your name is " + args[0] + "!");
    }
    }
    }[/code]
    Compile the code and run it. The program will not ask you about your name. Type your name as: java args name and press Enter key and program will show your name.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion