• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

System.in.read()

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,
I'm trying to learn Java through a couple of books and I need help. I haven't been able to compile a program that I copied exactly as written from the book. Here's the code:
public class Reply {
public static void main(String[] args) {
char a;
System.out.println("Enter a number from 1-3:");
a = (char)System.in.read();
switch(a) {
case '1':
System.out.println("\nYou win a car!");
break;
case '2':
System.out.println("\nYou picked the goat");
break;
case '3':
System.out.println("\nYou get to keep your 100");
break;
default:
System.out.println("\nIncorrect entry");
}


}
}
The problem is in the line of code:
a = (char)System.in.read();
The compiler puts a pointer under the parenthesis and says:7:Exception java.io.
IOException must be caught, or it must be declared in the throws clause of this method.
Would someone help me?
Thanks in advance.
Mike B.
 
MikeB
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I failed to say that the pointer is under the parenthesis after the word read, not the ones around char.
Thanks.
 
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You need to catch the IOException here. If you see the API documentation for System.in, you will notice that it is of type InputStream. This class has a method read(), which throws an IOException. So, whenever read() is being used, it is our responsibility to handle (catch) this exception. Otherwise the compiler would object.
All you need to do is, include System.in.read() inside a try block and then catch the IOException.

 
MikeB
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Mr. Saravanan for your help. After adding your code and adding import java.io.*;
as the first line of code, and then changing
char a to char a = 0, the program compiled.
Thanks again,
Mike B.
reply
    Bookmark Topic Watch Topic
  • New Topic