Forums Register Login

switch ??

+Pie Number of slices to send: Send
I am messing around with a program I made trying to test my knowledge of switch, but when I execute the following code, It does not print what it is supposed to.. What am I doing wrong here?..


Any help would be greatly appreciated...
+Pie Number of slices to send: Send
When you write a switch statement, it is always good practice to include a default block. If your added this:

to your statement you would see what the problem is. Have a look at the JavaDocs for InputStream's read() method: it is reading in bytes, not characters.
+Pie Number of slices to send: Send
I too tried u'r problem.I got the same result as that of you.I think the problem is u'r reading the input from keyboard and then u'r pressing enter.Then it's taking both input+ascii value of enter(48).So there is no output.Just add the following 2 lines after reading input
System.out.println(month);
month=month-48;

regards
Aparna
+Pie Number of slices to send: Send
Paul, thanks I will be checking into that, because I remember now reading about how it reads in bytes not characters.. I just learned getting input and switch, so I am going to stud a little more and see what I find..

Aparna, that code works up to number 9, then anything with a one in it shows January.. maybe you can't use too many cases in switch or something..
+Pie Number of slices to send: Send
Aparna, that code works up to number 9, then anything with a one in it shows January.. maybe you can't use too many cases in switch or something..

No, that's not the problem. The read() method reads just 1 byte. When you enter "12", there are two characters, not just one. You just read the first byte (the "1" of "12").

Try entering "24". It will print "February". Do you see why?

Instead of using System.in.read(), read the data another way, for example by using class Scanner:
+Pie Number of slices to send: Send
with System.in.read() are their parameters to modify how many byte you

want it to read??

Justin
+Pie Number of slices to send: Send
You can also add these 3 lines of code, and it will solve your problem.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String data = br.readLine();
month = Integer.parseInt(data);

See ya later boys, I think I'm in love. Oh wait, she's just a tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1027 times.
Similar Threads
Puzzled
enumerations
switch
Finding number of days in a month confusion
cannot find symbol inside String?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 23:18:28.