Click to See Complete Forum and Search --> : How to take console input


Harish Chandra
February 20th, 2000, 03:15 AM
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);
}
}

Johnson
February 21st, 2000, 08:14 AM
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

Johnson
February 21st, 2000, 08:28 AM
Hello

DataInputStream in = new DataInputStream(System.in);

int value = in.readInt();

happy coding
You can use this also
Johnson Philip