Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

read from standard in

 
Rock Manian
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to write my first ever java program. I don't know how to read in an int for example or a string. I'm a C++ programmer, and just now starting Java, that's my background. Here is what I already have:



And here is the error I get when I'm compiling:

prog4.java:38: unreported exception java.io.IOException; must be caught or declared to be thrown
line = in.readLine();
^
1 error

Any ideas? I tried using exception but I got the same error. What am I missing?
Thanks
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess you get a first error, when trying to omit 'System' in 'System.out'.

And you needn't import java.lang - it's automatically imported every time.

To your question:
Exceptions are thrown, when an error occurs, and the Library doesn't know how to handle it.
Maybe you can handle it.
If yes, catch it, and handle it.
If no, declare your method to throw it, so your caller might catch it.

Since we don't have a caller, we are on our own.
If System.in is in an errorstate, there isn't much what we can do.
But reporting the error is what we should do at least:


If the user inputs invalid stuff like "fourtytwo", the next exception occurs.
Here you have much better possibilities to react, if you try and catch the NumberFormatException: ask again for input.

In your program it isn't of much help, but in a complex program terminating on such an error is unfriendly.
 
Rock Manian
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had System.out declared, but I just didn't paste it in here. Ok, it worked the way you showed me.

Do you know how to print out a variable like let's say max?

Thanks
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you know how to print out a variable like let's say max?

System.out.print(max);
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic