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?..
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.
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;
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..
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: