Java n00b needs some help. reading strings

mchammer187

Diamond Member
Nov 26, 2000
9,114
0
76
How do I read in a string from the console?

so i am asking basically whats the equivalent of
char s[20];
cin.getline(s,20);

 

stev0

Diamond Member
Dec 9, 2001
5,132
0
0
errr... i know how to flowchart and write l337 psudocode... does that help?

stev0 <- java n00b in training :)
 

Kilrsat

Golden Member
Jul 16, 2001
1,072
0
0
Here's a few excerpts from one of my projects that involved many calls to the commandline:

//setup stuff

private static final BufferedReader STDIN = new BufferedReader( new InputStreamReader( System.in ) );

//getKeyboardReader, to get input from the user
public static final BufferedReader getKeyboardReader()
{
return STDIN;
}


//code to actually get stuff from commandline, "input" becomes what was entered
//produces an IOException if the user does something really funky

try
{
BufferedReader stdin = RobotGame.getKeyboardReader();
input = stdin.readLine();
}

//catches an IOException if created here
catch (IOException ioe) {}
 

Kilrsat

Golden Member
Jul 16, 2001
1,072
0
0
Originally posted by: gopunk
whoa that's hella annoying.... why didnt' they make it easier? :confused:

Because with a few simple modifications on the code I posted, it can be used to read from a network source, a file on the drive, a telnet session :)

So while reading from the commandline might take a few extra steps, once you learn that, you're ready to tackle reading most anything.

 

mchammer187

Diamond Member
Nov 26, 2000
9,114
0
76
Originally posted by: Kilrsat
Originally posted by: gopunk
whoa that's hella annoying.... why didnt' they make it easier? :confused:

Because with a few simple modifications on the code I posted, it can be used to read from a network source, a file on the drive, a telnet session :)

So while reading from the commandline might take a few extra steps, once you learn that, you're ready to tackle reading most anything.

do you think you can post the easier way :D thanks for the help BTW
 

Jzero

Lifer
Oct 10, 1999
18,834
1
0
So while reading from the commandline might take a few extra steps, once you learn that, you're ready to tackle reading most anything.

Exactly. It's frustratingly complicated to just grab input from a command line, but the same tactic makes so many other forms of I/O fairly simple and you can use one piece of code to do a whole lot.

 

Jzero

Lifer
Oct 10, 1999
18,834
1
0
do you think you can post the easier way :D thanks for the help BTW

That IS the easier way ;)
In fact, I think it's about the only way. I mean, you can use other readers, but bufferedreader is the way to go for this.