Results 1 to 3 of 3
- 08-01-2007, 03:30 PM #1
Member
- Join Date
- Jul 2007
- Posts
- 40
- Rep Power
- 0
Problem with a switch statement in Java
I've been having this odd problem with a switch statement in Java.
The problem I'm having is that the switch statement doesn't seem to be recognizing the correct input. As an example, I'm checking for various characters, and i read them in as ints. The ASCII code for a ':' is 58, and when I test it like this:
it works fine, but the same input in a switch statement doesn't do anything:Java Code:if( input == 58){ do stuff; }
Thanks.Java Code:switch( input){ case 58: do stuff: break; }
- 08-01-2007, 07:18 PM #2
According to this test/exploration your code should work. I wonder if the variable input could be something other than a char.
Java Code:public class Test { public static void main(String[] args) { char[] chars = { 'a', 'b', 'c', 'd' }; explore(chars); String s = ""; for(int j = 0; j < chars.length; j++) { char c = chars[j]; switch(c) { case 'a': // both seem to // case 97: // work okay s = "a"; break; case 'b': // case 98: s = "b"; break; case 'c': // case 99: s = "c"; break; case 'd': // case 100: s = "d"; break; default: s = "default"; } System.out.printf("j = %d s = %s%n", j, s); } } private static void explore(char[] chars) { for(int j = 0; j < chars.length; j++) { char c = chars[j]; int n = (int)chars[j]; System.out.printf("j = %d c = %s n = %3d c == n = %b%n", j, c, n, c == n); } } }
- 08-02-2007, 04:43 AM #3
Senior Member
- Join Date
- Jul 2007
- Posts
- 130
- Rep Power
- 0
Similar Threads
-
Method in a Switch Statement
By cart1443 in forum New To JavaReplies: 6Last Post: 03-14-2008, 03:48 AM -
Switch Statement Help
By bluegreen7hi in forum New To JavaReplies: 6Last Post: 02-06-2008, 05:16 AM -
Switch statement to display the name of the month
By Java Tip in forum Java TipReplies: 0Last Post: 01-04-2008, 09:32 AM -
JavaScript to Java Statement
By mutuah in forum Advanced JavaReplies: 0Last Post: 08-08-2007, 05:16 AM -
Help with gigantamous switch statement
By trill in forum New To JavaReplies: 2Last Post: 08-06-2007, 08:11 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks