CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Feb 2000
    Posts
    2

    How to take console input

    I want to know how to receive console input in a program. You can use System.out.println for displaying something on the console. What is the corresponding way to receive an input?

    As an alternative way, I tried writing a small class myself for this purpose, but I am getting some errors that I am unable to understand. Can somebody please help with the following code:

    import java.io.*;

    class IoServices {
    public static int getInt () throws IOException {
    InputStream in = System.in;
    byte [] buffer = new byte [1024];
    in.read (buffer);
    String str = new String (buffer);
    return Integer.parseInt (str);
    }
    }

    class Testing {
    public static void main (String [] args) throws IOException{
    System.out.println ("Enter your age ");
    int age = IoServices.getInt ();
    System.out.println ("You entered " + age);
    }
    }




  2. #2
    Join Date
    Jan 1999
    Location
    India , Kerala
    Posts
    3

    Re: How to take console input

    hello

    Please try my this simple code

    import java.io.*;
    import java.util.*;

    public class Apple
    {
    public static void main(String[] ar)
    {
    test t=new test();
    try{
    int myvalue=0;
    int yourvalue=0;
    int end=21;
    String strInput;
    DataInputStream in=new DataInputStream(new BufferedInputStream(System.in));

    System.out.println("THERE ARE 21 APPLES IN THE BOX"+"\n"+" YOU ARE GIVEN THE OPTION TO CHOOSE MAXIMUM OF FOUR APPLES AT A TIME"+"\n\r"+"AT THE END ONE WHO SELECT THE LAST REMAINING APPLES WILL WIN THE GAME:" );
    while(end!=1)
    {
    System.out.println("\n\n\nENTER YOUR CHOICE :");
    strInput=in.readLine();
    Integer a=new Integer(strInput);
    yourvalue=a.intValue();
    while(yourvalue>4)
    { System.out.println("ENTER YOUR NEXT CHOICE :");
    strInput=in.readLine();
    a=new Integer(strInput);
    yourvalue=a.intValue();

    }

    myvalue=(5-yourvalue);
    System.out.println("I SELECTED "+myvalue +" APPLES:");
    end=end-(myvalue+yourvalue);

    }
    if(end==1)
    System.out.println("\n\n\n\n SORRY YOU LOST THE GAME !!");

    }catch(IOException e){System.out.println("Errror");}
    }
    }


    happy coding
    Johnson Philip


  3. #3
    Join Date
    Jan 1999
    Location
    India , Kerala
    Posts
    3

    Re: How to take console input

    Hello

    DataInputStream in = new DataInputStream(System.in);

    int value = in.readInt();

    happy coding
    You can use this also
    Johnson Philip





Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured