|
-
Jul 6th, 2002, 03:11 PM
#1
how can I use conditions in switch statement
well?
also something like this (I'm showing the VB example, hope someone can tell me how to do this in java )
VB Code:
Select case num
case is > 5
' do something
' ......
end select
Last edited by MrPolite; Jul 6th, 2002 at 03:14 PM.
-
Jul 6th, 2002, 04:11 PM
#2
Dazed Member
Here is some code that i had which contains a switch statement.
The main thing to remember when using switch statements is that the expression associated with it must have a byte, char, short or int value. The floting point and boolean types are not supported, and neither is long, even though long is an integer type.
Code:
import java.io.*;
import java.util.*;
class VowelGrabber{
public static void main(String[] args){
try{
File f = new File("C://Java/text.txt");
BufferedReader buff = new BufferedReader(new FileReader(f));
while(true){
String x = buff.readLine();
if(x == null) break;
x.toLowerCase();
StringTokenizer st = new StringTokenizer(x);
while(st.hasMoreTokens()){
grabVowels(st.nextToken());
}
}
}catch(IOException e){System.err.println(e);}
}
public static void grabVowels(String s){
int numofvowels = 0;
for(int i = 0; i < s.length(); ++i){
char c = s.charAt(i);
switch(c){
case 'a':
numofvowels++;
break;
case 'e':
numofvowels++;
break;
case 'i':
numofvowels++;
break;
case 'o':
numofvowels++;
break;
case 'u':
numofvowels++;
break;
}
}
System.out.println(" String " + s + " encountered " + numofvowels + " vowels ");
numofvowels = 0;
}
}
-
Jul 6th, 2002, 05:42 PM
#3
tnx Dilenger4 for the reply, but I'm looking for something that does exactly the same thing as the VB code that I posted I know how to use the case the way you said it, but I want it to check for a condition, kinda like an if statement. see the example in the first post plz
thank you
-
Jul 6th, 2002, 08:32 PM
#4
Dazed Member
I guess i would juast wrap up the switch statement in an if.
Code:
public class test{
public static void main(String[] args){
selectCase(12);
}
public static void selectCase(int i){
if(i > 5){
switch(i){
case 6: System.out.println("six");
break;
case 7: System.out.println("seven");
break;
default:
System.out.println("number is greater then 5 but not six or seven");
}
}
}
}
Last edited by Dilenger4; Jul 6th, 2002 at 08:36 PM.
-
Jul 6th, 2002, 11:23 PM
#5
-
Jul 6th, 2002, 11:40 PM
#6
Originally posted by MrPolite
So basically Java doesnt support that? right?
Correct...in Java, as well as C/C++ and other languages, the case statements must be a constant integral value. Example...
Code:
int a = 1, b = 1;
switch (a)
{
case 1: //legal
case 1.5: //illegal - not an integral
case b: //illegal - not a constant
}
Laugh, and the world laughs with you. Cry, and you just water down your vodka.
Take credit, not responsibility
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|