This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

confused with in.readLine();

 
Dustin Schreader
Ranch Hand
Posts: 74
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok this sounds simple enough but here is my problem, when I try to choose option 6 I prompt the console to have an item entered but no input text option pops up it just goes straight into prompting to Please enter price and just skips over entering item. Not really sure what I'm doing wrong here.
 
Winston Gutkowski
Bartender
Pie
Posts: 9472
50
Eclipse IDE Hibernate Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dustin Schreader wrote:Not really sure what I'm doing wrong here.

Well your title asks about readLine(), but you're running read().

If you want the first, you have to to wrap System.in in a BufferedReader:
BufferedReader keyboard =
   new BufferedReader(new InputStreamReader(System.in));


A bit ugly, I know (I wish Java would fix that).

readLine() also returns a String, so you need to pull the first character from it:
cmd = keyboard.readLine().charAt(0);

It should be noted that with readLine(), the character won't be read until you press the Enter key.

Another alternative, popular with beginners, is java.util.Scanner.

Winston
 
Campbell Ritchie
Sheriff
Pie
Posts: 47250
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I’d go for Scanner.

Beware of read(); it returns the last character as an int and is not at all user-friendly.
 
Dustin Schreader
Ranch Hand
Posts: 74
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it to work with the read(); thanks for the help. I tried it with the Scanner but I got the same problem.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47250
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is because the Scanner#readLine() method doesn’t do what you think it does. Look here for discussion of a similar problem.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47250
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It’s not readLine() but nextLine(). Sorry for the mistake.
 
Rumesh Eranga
Ranch Hand
Posts: 34
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use Console object also(to read a line).

Console c = System.console();
String myString = c.readLine("Please enter a text to read : ");

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic