[1807] in java-interest
Re: switch
daemon@ATHENA.MIT.EDU (Patrick Simpson)
Sun Sep 17 21:11:33 1995
Date: Sun, 17 Sep 1995 11:11:21 -0800
To: prepapol@lifl.fr, java-interest@java.sun.com
From: psimpson@qualcomm.com (Patrick Simpson)
>Hello,
>
>I've compiled this :
>
>class Switch{
> public static void main(String args[]){
> do{
> switch((int)System.in.read()){
> case 0: System.out.println("cas"+0);break;
> case 1: System.out.println("cas"+1);break;
> case 2: System.out.println("cas"+2);break;
> case 3: System.out.println("cas"+3);break;
> default: System.out.println("Terminated");break;
> }
> }while(true);
> }
>}
>
>and I've this execution
>
>%java Switch
>0
>Terminated
>Terminated
>1
>Terminated
>Terminated
>3
>Terminated
>Terminated
>4
>Terminated
>Terminated
>...
>
>Is anybody have an idea ? I haven't found a light solution about the syntax
>of switch in the doc...
>
>Thanks
>
>-------------------------------------------------
>Bruno CUVELIER e-mail: prepapol@lifl.fr
>
>Universite des Sciences et Technologies de Lille
>Laboratoire d'Informatique Fondemmentale de Lille
>Cite Scientifique
>U.F.R. d'IEEA, batiment M3
>59655 Villeneuve d'Ascq CEDEX.
>FRANCE
>-------------------------------------------------
>
>-
>Note to Sun employees: this is an EXTERNAL mailing list!
>Info: send 'help' to java-interest-request@java.sun.com
I think your problem lies in the fact that System.in.read() returns an int
those value is the byte entered. When you enter `1' on the input line you
are also entering the `\n' character (10). When you enter the switch
statment the first value to get read is 49 (1 in ASCII/Unicode) which cause
your default to be called. Next the newline character 10 (`\n' in
ASCII/Unicode) is sent threw and also causes your default to be called. Now
the program bloack for new input. Try using '1' instead of 1 as your case
value, and have a dummy case statement for the '\n' character. This should
fix your problem. example:
class Switch{
public static void main(String args[]){
boolean escape = false;
do{
switch(System.in.read()){ // already return an int
case '0': System.out.println("cas"+0);break;
case '1': System.out.println("cas"+1);break;
case '2': System.out.println("cas"+2);break;
case '3': System.out.println("cas"+3);break;
case '\n': /* do nothing */ break;
default: System.out.println("Terminated"); escape = true; break;
}
}while(escape = false);
}
}
Hope that helps!
-Patrick
Patrick Allen Simpson
Qualcomm Inc
6455 Lusk Blvd.
San Diego, CA 92121-2779
ph: (619) 658 4071
fax: (619) 658 2230
email: psimpson@qualcomm.com
office: Q-205-O
*/* The opinions expressed within are mine and do not necessarily reflect
*/* those of my Employer.
-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com