Howdy, Stranger!

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

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Input from keyboard

rashmigalagalirashmigalagali Posts: 2Member
Can anyone please explain how to read an input to a java code from keyboard.Please explain with an example.

Thanks & Regards,

Rashmi

Comments

  • paycitypaycity Posts: 4Member
    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.