Switch statement loops
Hi,
I was just wondering if there is any way to make a switch statement loop back on itself, for example if you want to use the default part of the switch statement check the validity of the inputs themselves and ask for a replacement input should the data not meet the criteria?
Thanks,
Luke.
I was just wondering if there is any way to make a
switch statement loop back on itself, for example if
you want to use the default part of the switch
statement check the validity of the inputs themselves
and ask for a replacement input should the data not
meet the criteria?switch statement is not supposed to loop. So, you would have to make use of a for or while with some criterion determined by the execution of the switch statement.
Similar Messages
-
A function containing switch statement and foreach-object loop
Hello Guys
in my testdomain.lab, i have following five OUs in mt test AD structure:
'OUusers', 'OUcomputers','OUservers','OUadministrators','OUhelpdesks'.
i have created following five variables:
$OUusers = 'ou=OUusers,dc=mytestdomain,dc=lab'
$OUcomputers = 'ou=OUcomputers,dc=mytestdomain,dc=lab'and so on
now i have created a function which gets this names as input &
foreach-object creates the related OU.
but the problem is sometimes when i run my function, maybe some of those five OUs
currently exist in AD so this will cause a
terminating error.
so i know i must use switch statement to define conditions like this:
if $OUusers doesn't exist, execute this : new-ADOrganizationalunit $OUusers
if $OUcomputers doesn't exist, execute this : new-ADOrganizationalunit $OUcomputers
and so on...
it's a long time which i am trying to create a
function which contains such switch statement & properly forEach-object loop.
i have studied switch and foreach-object loops , but this scenario is complicated for me & i was unable to get the correct code.
Function createOUs {
# combination of ForEach-Object and Switch statement here
may someone give me the correct
command please?
thanks a lotLike this:
$CompanyRoot=tha'ou=MyCompany, dc=mytestdomain,dc=lab'
New-ADOrganizationalUnit -Name MyCompany -ErrorAction SilentlyContinue
$ous='Users', 'Computers','Servers','Administrators','Helpdesk'
foreach($ou in $ous){
New-ADOrganizationalUnit -Name $ou -Path $companyroot -ErrorAction SilentlyContinue
¯\_(ツ)_/¯
jrv, That can't be the solution because when you running a command which tries to creates an OU
which already exist in AD, causes a
terminating error which has two caveats:
1- shows red error message on screen
2- stops and doesn't continue to execute next lines of code
Note that -ea silentlycontinue and -ea ignore have no effect on
terminating errors and they cn't hide error messages, also script can't continue.
i examined that.
to get sure, run this function in your test AD & see the result:
function createOUs {
New-ADOrganizationalUnit -Name 'an-existing-ou' -Protected 0 -ea SilentlyContinue # you see that -ea silentlycontinue has no effect here
New-ADOrganizationalUnit -Name '2ndOU' -Protected 0 -ea SilentlyContinue # you see that because the previous error has been a terminating error, command execution has been stopped and this 2nd OU hasn't been creatde
another bad news is ( as i tested), if we query for an Organizational Unit which doesn't exist in AD , it generates a terminating error as well, so again here -ea has no effect.
test this:
PS C:\> Get-ADOrganizationalUnit -identity 'ou=nonesense,dc=yourDomain,dc=lab' -ea ignore
error doesn't disapear ;-) -
Java Program.. HELP (switch statement)
I need help on fixing this program for school.ive looked at information online but i still do not see what i am doing wrong.
The College Rewards Program is based on a student�s achievements on the ACT Test. Students that have excelled on the test are going to be rewarded for the hard work that they put into high school and studying for the exam. The following are the rewards that will be given to students. They are cumulative, and they get all rewards below their score.
1. 35-36 $100 a week spending money
2. 33-34 Free computer
3. 31-32 $10,000 free room and board
4. 25-30 $5000 off the years tuition
5. 21-24 $500 in free books per year
6. 17-20 Free notebook
7. 0-16 Sorry, no rewards, please study and try taking the ACT again.
Make a prompt so the user is asked for their ACT score( be careful).
Change the ACT score into a number
Then have the program use that number to display a message about the Rewards program.
Sample output:
What was your score on the ACT: 44
Entry error, please enter a number from 0 to 36. (error trap wrong numbers)
What was your score on the ACT: 27
You got a 27 on the ACT, your rewards are: ( have it number the rewards)
1. $5,000 off the year�s tuition
2. $500 dollars a year in books
3. A free notebook
Congratulations on your hard work and good score.
import java.util.Scanner;
import java.text.*;
public class Act
public static void main (String [] args)
Scanner scan = new Scanner( System.in );
int score,reward;
score=0;
boolean goodnum;
do
System.out.println( "What was your ACT score? " );
score = scan.nextInt() ;
if (score >0 || score <36) goodnum = true;
else
System.out.println ("Please enter the correct number");
goodnum=false;
while (score<0 || score>36) {
if (score==35 || score==36) reward=1;
else if (score ==34 || score score==33) reward=2;
else if (score==32 || score==31) reward=3;
else if (score>=25 && score<=30) reward=4;
else if (score>=21 && score<=24) reward=5;
else if (score>=17 && score<=20) reward=6;
else reward=7;
c=0
switch (reward) {
case 1: $100 a week spending money
c++
System.out.println ("$100 a week spending money");
case 2: Free computer
c++
System.out.println ("Free computer");
case 3: $10,000 free room and board
c++
System.out.println ("$10,000 free room and board");
case 4: $5000 off the years tuition
c++
System.out.println ("$5000 off the years tuition");
case 5: $500 in free books per year
c++
System.out.println ("$500 in free books per year");
case 6: Free notebook
c++
System.out.println ("Free notebook");
case 7: Free notebook
c++
System.out.println ("Sorry, no rewards, please study and try taking the ACT again.");
break;
default:
System.out.println ("Sorry, no rewards, please study and try taking the ACT again.");
break;
}There are some strange things going on here that could be fixed, so I'll just put my version of how i'd handle this up.
import java.util.Scanner;
import java.text.*; // is this really needed? Scanner's the only class I see
public class Act {
public static void main( String[] args ) {
Scanner scan = new Scanner( System.in );
int score, reward; // don't need to set a value yet
boolean goodnum;
do {
System.out.println( "What was your ACT score? " );
score = scan.nextInt();
if ( score >= 0 && score <= 36 ) goodnum = true; // note the && and =s
else {
System.out.println( "Please enter a valid number (between 0 and 36)." );
goodnum = false;
} while ( !goodnum ); // when this loop finished, the number will be between 0 and 36, a good number
if ( score >= 35 ) reward = 1; // save yourself the typing, by now score must be between 0 and 36
else if ( score >= 33 ) reward = 2; // so just go down with else ifs.
else if ( score >= 31 ) reward = 3; // this will only reach the lowest point.
else if ( score >= 25 ) reward = 4;
else if ( score >= 21 ) reward = 5;
else if ( score >= 17 ) reward = 6;
else reward = 7;
// what was the c for? reward already tells how well they did
// You handled the switch statement almost perfectly
// don't break so that reward progressively adds to the output
if ( reward >= 6 ) { // this if statement is optional, just for good esteem. You could even take it out of the if{}
System.out.println( "For your score of "+String.valueOf( score )+" you will be rewarded the following:" );
switch ( reward ) {
case 1: // $100/week spending money
System.out.println( "$100 a week spending money." );
case 2: // Free computer
System.out.println( "Free computer." );
case 3: // $10,000 room and board
System.out.println( "$10,000 free room and board." );
case 4: // $5000 off tuition
System.out.println( "$5000 off the year's tuition." );
case 5: // $500 in free books per year
System.out.println( "$500 in free books per year." );
case 6: // Free notebook
System.out.println( "Free notebook." );
break; // break here to keep away from discouraging the fine score
case 7: // since 7 and default are the same result, ignore this and it'll pass to default
default: // but technically, since reward must be from 1 to 7, default would never explicitly be called
System.out.println( "Sorry, no rewards. Please study and try taking the ACT again." );
break; // likely this break is unneccessary
}That works in my head, hope it works on your computer. -
Newbie question about switch statement
Lets say you have a loop and inside the loop you have a switch statement, how do you BREAK out of the outer loop?
for (i=0....) {
switch {
case 11:
.... some stuff
break; <==== HOW DO I BREAK OUT OF THE for loop here?In standard C and standard C++ the break statement terminates the nearest enclosing loop and only that loop; i.e. control transfers to the first statement following the loop. I think there are C or C++ extensions that allow loop tags which may be used with a break to specify which loop to drop through, but I don't think these are supported by gcc, and they would certainly be very non-portable.
There are several common ways to drop out of one or more outer loops. In many cases, there's nothing else in the loop following the switch so you can simply write
switch (condition) {
default:
case 0:
break;
// other case statements here
break;
Else you can declare a loop control var and use the continue statement like this:
for (i=0; i<jMax && !bDone; i++) {
switch (condition) {
default:
case 0:
bDone++; continue;
// other case statements
If you need to escape several loops and/or don't want to use loop control vars, you might consider structuring the code so you can use return to terminate the entire function. In the worst case of a very complex structure that you don't know how to simplify with a helper function, you can always resort to a goto:
switch (condition) {
default:
case 0:
goto escape;
// other case statements here
// remainder of code inside nested loops here
escape: <first statement following the outermost loop>;
Note that the statement following the escape label is always executed; i.e. when execution skips the goto it's as if the statement following escape was unlabeled. Use goto sparingly of course, since it's an artifact of unstructured programming. But when you really need a goto, it can make your code much easier to maintain. -
Problem with switch-statement & ä, ö, ü
Hi all,
I am doing this Java online tutorial right now and have a problem with one of the exercises. Hopefully you can help me:
I have to write a program that determines the number of consonants, vowels, punctuation characters, and spaces in an input line. I found a solution, but have two questions about it:
Im unable to calculate the amount of umlauts (ä, ö, ü). Somehow the program doesnt recognize those characters. Why?
In general Im not very happy with this huge list of cases. How would you solve a problem like this? Is there a more convenient/elegant way?
Thanks in advance!
Write a program that determines the number of consonants, vowels, punctuation characters, and spaces in an input line.
Read in the line into a String (in the usual way). Now use the charAt() method in a loop to access the characters one by one.
Use a switch statement to increment the appropriate variables based on the current character. After processing the line, print out
the results.
import java.util.Scanner;
class Kap43A1
public static void main ( String[] args )
String line;
char letter;
int total, countV=0, countC=0, countS=0, countU=0, countP=0;
Scanner scan = new Scanner(System.in);
System.out.println( "Please write a sentence " );
line = scan.nextLine();
total=line.length(); //Gesamtanzahl an Zeichen des Satzes
for (int counter=0; counter<total; counter++)
letter = line.charAt(counter); //ermitteln des Buchstabens an einer bestimmten Position des Satzes
switch (letter)
case 'A': case 'a':
case 'E': case 'e':
case 'I': case 'i':
case 'O': case 'o':
case 'U': case 'u':
countV++;
break;
case 'B': case 'b': case 'C': case 'c': case 'D': case 'd': case 'F': case 'f': case 'G': case 'g': case 'H': case 'h':
case 'J': case 'j': case 'K': case 'k': case 'L': case 'l': case 'M': case 'm': case 'N': case 'n': case 'P': case 'p':
case 'Q': case 'q': case 'R': case 'r': case 'S': case 's': case 'T': case 't': case 'V': case 'v': case 'W': case 'w':
case 'X': case 'x': case 'Y': case 'y': case 'Z': case 'z':
countC++;
break;
case ' ':
countS++;
break;
case ',': case '.': case ':': case '!': case '?':
countP++;
break;
case 'Ä': case 'ä': case 'Ö': case 'ö': case 'Ü': case 'ü':
countU++;
break;
System.out.println( "Total amount of characters:\t" + total );
System.out.println( "Number of consonants:\t\t" + countC );
System.out.println( "Number of vocals:\t\t" + countV );
System.out.println( "Number of umlauts:\t\t" + countU );
System.out.println( "Number of spaces:\t\t" + countS );
System.out.println( "Number of punctuation chars:\t" + countP );
}WRE wrote:
In general Im not very happy with this huge list of cases. How would you solve a problem like this? Is there a more convenient/elegant way?I've been doing this a lot lately myself evaluating documents with 20 or so million words. Few tips:
1. Regular expressions can vastly reduce the list of cases. For example you can capture all letters from a to z or A to Z as follows [a-zA-Z]. To match a single character in a String you can then make use of the Pattern and Matcher classes, and incorporate the regular expression. e.g.
//Un-compiled code, may contain errors.
private Pattern letterPattern = Pattern.compile("[a-zA-Z]");
public int countNumberOfLettersInString(final String string) {
int count = 0;
Matcher letterMatcher = letterPattern.matcher(string);
while(letterMatcher.find()) {
count++;
return count;
}2. As mentioned above, Sets are an excellent choice. Simply declare a static variable and instantiate it using a static initializer block. Then loop over the String to determine if the character is in the given set. e.g.
//Un-compiled code, may contain errors.
private static Set<Character> macrons = new HashSet<Character>();
static {
macrons.add('ä');
macrons.add('ö');
macrons.add('ü');
public int countNumberOfMacronsInString(final String string) {
int count = 0;
for(char c : string.toCharArray()) {
if(macrons.contains(c) {
count++;
return count;
}Mel -
Continue in a switch statement
What is the difference between using unlabelled continue and break in a switch statement?
Looks like there is the same effect but I didn't found anything about using continue in switch in any documentation.
Here's a typical explanation of using switch statement:
"If the condition in a +switch statement+ matches a case constant, execution will run through all code in the +switch+ following the matching case statement until a +break statement+ or the end of the +switch statement+ is
encountered. In other words, the matching case is just the entry point into the case block, but *unless there's a break statement*, the matching case is not the only case code that runs"
Is it a good practise to use continue instead of break in such case?Books are right again :))
Thanks everybody who wrote here.
As I found out continue is only for use in the loop statements. I just use continue inside both for and switch statements and that's why I thought that it's appropriate to use it inside switch. No way!! In this way continue will affect only loop, not switch statement.
For example:
class BreakTest {
public static void main(String[] args) {
BreakTest br = new BreakTest();
br.testContinue();
br.testBreak();
public void testContinue() {
int[] int_arr = { 0, 0, 0, 0, 1, 0, 0 };
int count_in_switch = 0;
int count_in_for = 0;
for (int a : int_arr) {
switch (a) {
case 0:
continue;
default:
count_in_switch++;
count_in_for++;
System.out.println("count_in_switch=" + count_in_switch
+ " count_in_for=" + count_in_for);
public void testBreak() {
int[] int_arr = { 0, 0, 0, 0, 1, 0, 0 };
int count_in_switch = 0, count_in_for = 0;
for (int a : int_arr) {
switch (a) {
case 0:
break;
default:
count_in_switch++;
count_in_for++;
System.out.println("count_in_switch=" + count_in_switch
+ " count_in_for=" + count_in_for);
count_in_switch=1 count_in_for=*1*
count_in_switch=1 count_in_for=*7*
In case of using continue you won't get to count_in_for++; - you'll jump to the next iteration of for loop.
In case of using break you'll go out of switch and go to next statement, that goes after switch block -
I am creating a class that extends object. I am using JOptionPane for input. I have a switch statement that I am using to call other methods, such as displaying a flag using GraphicsPen. Everything works great except when the switch calls the flag method and displays the flag, I can't close the flag until I end the switch method. I have a " for(;;) " statement that encloses the main method so the switch method will continue after each iteration.*********HELP*********PLEASE!*****************
class switchflags extends Object //class declaration
public static void main (String[]args) //main method
final String TITLE = "SWITCH"; //title for dialogs
for (;;) //loop
String switchstring = JOptionPane.showInputDialog //dialog for input
(null,"Select which program you want to use from below.\n\n"+
"*******Press enter when finished*******\n\n"+
"Enter 0 : to Quit\n"+
"Enter 1 : to see the Dutch Flag\n"+
"Enter 2 : to see the Mauritius Flag\n"+
"Enter 3 : to see the Italian Flag\n"+
"Enter 4 : to see the Norwegian Flag\n"+
"Enter 5 : to calculate Fibonacci number (n)\n"+
"Enter 6 : to calculate Miles Per Gallon\n\n",TITLE,JOptionPane.INFORMATION_MESSAGE);
int switchint = Integer.parseInt(switchstring); //convert string to a integer
if (switchint == 0) //exit if 0 was entered
JOptionPane.showMessageDialog
(null,"Thanks for using this program.\nHave a nice day!",TITLE,JOptionPane.PLAIN_MESSAGE);
System.exit(0); //end program
else if (switchint < 0) //show error for invalid numbers less than zero
JOptionPane.showMessageDialog
(null,"*******ERROR*******\n\nEnter a number\nbetween (1 - 6).\n\nOr (0) to Quit.\n\n",
TITLE,JOptionPane.ERROR_MESSAGE);
else if (switchint > 6) //show error for invalid numbers greater than six
JOptionPane.showMessageDialog
(null,"*******ERROR*******\n\nEnter a number\nbetween (1 - 6).\n\nOr (0) to Quit.\n\n",
TITLE,JOptionPane.ERROR_MESSAGE);
switch (switchint) //test variable that was entered
case 1: DutchFlag1.start(); //display Dutch flag
break;
case 2: mauritius.start(); //display Mauritius flag
break;
case 3: italy.start(); //display Italy flag
break;
case 4: norway.start(); //display Norway flag
break;
case 5: FIBONACCI.start(); //run Fibonacci program
break;
case 6: MPG.start(); //run MPG program
break; -
Hi,
I've got a little question about the switch()-case statement.
let's consider the statement:
1: switch( nr){
2: case 1:
3: Vector vect = new Vector();
4: break;
5: case 2:
6: Vector vect = new Vector();
7: break;
8: }
At compile time, the compiler complains about line 6, he says the vect is allready defined.
But, when you take for example the if statement:
if ( bool)
Vector vect;
else
Vector vect;
he won't complain (dunno if java uses lazy evaluation).
of course one of the arguments for giving the error is that if you don't put the break, the switch will loop. but a for() loop does the same thing, yet there you can define the Vector inside the body (allthough it's not nice design).
besides that since switch is actually a nested if-statement, then it should be able to compile the above switch statement.
so, what are the real reasons it's not possible???
Tomlet's consider the statement:
1: switch( nr){
2: case 1:
3: Vector vect = new Vector();
4: break;
5: case 2:
6: Vector vect = new Vector();
7: break;
8: }
At compile time, the compiler complains about line 6,
he says the vect is allready defined.
But, when you take for example the if statement:
if ( bool)
Vector vect;
else
Vector vect;
he won't complain (dunno if java uses lazy
evaluation).It should complain! If you can compile the example if statement above, then I'd suggest your compiler has a bug in it.
of course one of the arguments for giving the error is
that if you don't put the break, the switch will loop.The argument for giving the error is that the scope of any variable declaration is its smallest enclosing block (delimited by braces).
but a for() loop does the same thing, yet there you
can define the Vector inside the body (allthough it's
not nice design).1. Only if the body is a block.
2. It is good design to keep your variable scope small.
besides that since switch is actually a nested
if-statement, Is it?
then it should be able to compile the
above switch statement.
so, what are the real reasons it's not possible???See above - If you put braces around the body of each case statement, you will be able to do what you are trying to do. -
Hi,
This might seem strange since normally when you write a switch statement you only use one char or integer, but how would you write a case that would accept two chars as its arg?
quick pseudo code.......
switch(input){
case ??:
case af:
etc etc..I think I'm using the wrong arguement equalsIgnoreCase, but I'm not sure what else to use... I want to be able to go through these options until "lq" is typed and then it will display the list I've created and quit the loop.. Could anyone give me a clue at what I can do?
Thanks in advance!
while(status)
System.out.print("Option (?? for help): ");
input = keyboard.next();
if (input.equalsIgnoreCase("??"))
System.out.println("\n" + "??" + " display these options" +
"\n" + "af" + " add given item as first" +
"\n" + "an" + " add given item while preserving natural order" +
"\n" + "rf" + " remove first item and report success" +
"\n" + "rg" + " remove first occurrence of given item and report success" +
"\n" + "rn" + " remove first item which is not in natural order and report success" +
"\n" + "ld" + " display list" +
"\n" + "le" + " make list empty" +
"\n" + "ls" + " sort the list, using rn and an" +
"\n" + "lq" + " display list and quit");
else if (input.equalsIgnoreCase("af"))
System.out.println("Item: ");
else if (input.equalsIgnoreCase("an"))
System.out.println("Item: ");
else if (input.equalsIgnoreCase("rf"))
System.out.println("Test: ");
else if (input.equalsIgnoreCase("rg"))
System.out.println("Test: ");
else if (input.equalsIgnoreCase("rn"))
System.out.println("Test: ");
else if (input.equalsIgnoreCase("ld"))
System.out.println("Test: ");
else if (input.equalsIgnoreCase("le"))
System.out.println("Test: ");
else if (input.equalsIgnoreCase("ls"))
System.out.println("Test: ");
else if (input.equalsIgnoreCase("lq"))
System.out.println("Test: ");
} -
Beginner question regarding switch statements with arrays....
Doing a little project for my beginner's object oriented programming course. I've written the following code, but the switch statement won't recognize my array values....I'm required to use a switch statement in my program, which will count various character types in an external file....any insight is appreciated.
import java.io.*;
public class MyProg
public static BufferedReader inFile;
public static void main(String[] args)
throws IOException, StringIndexOutOfBoundsException
String line;
inFile = new BufferedReader(new FileReader("TME5Part1.dat3"));
char UpperCase[]= {'A','B','C','D','E','F','G','H','I','J','K','L','M',
'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
char LowerCase[]= {'a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z'};
char Digit[]= {'0','1','2','3','4','5','6','7','8','9'};
char EndMark[]= {'!','.','?'};
char MidMark[]= {',',':',';'};
char symbol;
int upperCaseCt = 0;
int lowerCaseCt = 0;
int digitCt = 0;
int endMarkCt = 0;
int midMarkCt = 0;
int spaceCt = 0;
int otherCharCt = 0;
line = inFile.readLine(); //read first line (priming read)
while (line != null) // Loop until end of data (empty line)
for (int count = 0; count < line.length(); count++) // Loop until end of line
symbol = line.charAt(count);
for (int i=0; i<=25;i++)
char uppercase=UpperCase; //get array values for i
char lowercase=LowerCase[i];
if (i<=9) {char digit=Digit[i];}
if (i<=2) { char endmark=EndMark[i];
char midmark=MidMark[i];
switch(symbol)
case uppercase : upperCaseCt++;
break;
case lowercase : lowerCaseCt++;
break;
case digit : digitCt++;
break;
case endmark : endMarkCt++;
break;
case midmark : midMarkCt++;
break;
case ' ' : spaceCt++;
break;
default : otherCharCt++;
break;
line = inFile.readLine();
System.out.println("Number of uppercase letters = "+upperCaseCt);
System.out.println("Number of lowercase letters = "+lowerCaseCt);
System.out.println("Nubmer of digits = "+digitCt);
System.out.println("Number of end punctuation marks = "+endMarkCt);
System.out.println("Number of mid punctuation marks = "+midMarkCt);
System.out.println("Number of spaces = "+spaceCt);
System.out.println("Number of other characters = "+otherCharCt);
I was trying to do it this way rather than "case 'A':
case 'B':
case 'Z:" for each type of 'symbol'.
Unfortunately, the switch statement is required or this would be easier with arrays and for loops...I'm not sure if my code is even possible. Thanks in advance =)
Edited by: RiTarDidRiTarDid wrote:
For sure it is the most straightforward way, but my curiosity is getting the better of me....I will most likely submit the program with the longer (value-by-value) switch method, as I haven't found anyone who can tell me how to properly reference an array value in a 'case'.Well, you can do this (basically):
switch(some_array[some_index]) {
case 'a': blahblah
case 'z': blahblah
}What you can't do is this:
switch(some_scalar_value) {
case a_whole_array: blahblah
case a_whole_another_array: blahblah
}Because the latter isn't what "case" means.
If you want to do something like the latter, use if/else statements. Here's a dirty little industry secret: people seldom use switch/case. if/else is a lot more common.
Actually that dirty little secret isn't really particular dirty or particularly secret. It is, however, little.
I just recall a suggestion to use arrays for any group that is more than 10 values in size;Well...sort of...
You should use the expression of data that's appropriate for what the data is. If it's a collection of data of the same kind and an ordering, then an array or a java.util.List makes sense. If it's data that is of the same kind but no ordering and no duplicates are allowed, use a java.util.Set. (Etc. on this front.) If it's a collection of un-alike data, but which belongs in associated groups (e.g., a user's name, age, height, and whether s/he's married) then you should create a class that represents that logical grouping. Etc. If you have more than 10 individual data that can't be grouped or collected somehow, then chances are you need to rethink what's happening.
so I wanted to see if an array could be employed for comparisons with the 'switch' statement. The program is simple enough, I'm just trying to flex my problem-solving muscle in different ways. :)
thanks for replying, hope I can get a definite "yes, it can be done this way" or "no it can't" if there's anyone out there who knows.....The problem is that your example is contrived. So you can do a variety of things that fit into the contrivance, but they'd be weird things.
In practice, you'd want to use the character classification methods in Character, if you wanted to characterize a bunch of characters. Or maybe a regular expression. There's no need to keep an array of characters to match against if you want to determine whether a particular character is upper case. In fact, that's the wrong way of doing things, because Character.isUpperCase is more likely to tell whether any character (not just stuff that's also an element of ASCII) qualifies as upper case. -
HELP -menu using a switch statement
Hello to all. I'm new to the Java world, but currently taking my first Java class online. Not sure if this is the right place, but I need some help. In short I need to write a program that gives the user a menu to chose from using a switch statement. The switch statement should include a while statement so the user can make more than one selection on the menu and provide an option to exit the program.
With in the program I am to give an output of all counting numbers (6 numbers per line).
Can anyone help me with this?? If I'm not asking the right question please let me know or point me in the direction that can help me out.
Thanks in advance.
Here is what I have so far:
import java.util.*;
public class DoWhileDemo
public static void main(String[] args)
int count, number;
System.out.println("Enter a number");
Scanner keyboard = new Scanner (System.in);
number = keyboard.nextInt();
count = number;
do
System.out.print(count +",");
count++;
}while (count <= 32);
System.out.println();
System.out.println("Buckle my shoe.");
}Thanks for the reply. I will tk a look at the link that was provided. However, I have started working on the problem, but can't get the 6 numbers per line. I am trying to figure out the problem in parts. Right now I'm working on the numbers, then the menu, and so on.
Should I tk this approach or another?
Again, thanks for the reply. -
How to convert switch statement into iif than else statement in SSRS
Hi All;
How do i convert switch statement into iif statement in ssrs
=
Switch(
Fields!createdonValue.Value = Now(), "Today",
Fields!createdonValue.Value = DateAdd("d",-1,Today()),"Yesterday",
Fields!createdonValue.Value >= FORMATDATETIME(DateAdd(DateInterval.Day, -6,DateAdd(DateInterval.Day, 1-Weekday(today),Today)),DATEFORMAT.ShortDate) and
Fields!createdonValue.Value <= FORMATDATETIME(DateAdd(DateInterval.Day, -0,DateAdd(DateInterval.Day, 1-Weekday(today),Today)),DATEFORMAT.ShortDate),"Last Week",
Fields!createdonValue.Value >= FORMATDATETIME(DateAdd(DateInterval.Day, -13,DateAdd(DateInterval.Day, 1-Weekday(today),Today)),DATEFORMAT.ShortDate) and
Fields!createdonValue.Value <= FORMATDATETIME(DateAdd(DateInterval.Day, -0,DateAdd(DateInterval.Day, 1-Weekday(today),Today)),DATEFORMAT.ShortDate),"Last Fortnight",
Fields!createdonValue.Value >= DateValue(DateAdd("M",-1,DateAdd("D",-(Day(Now)-1),Now))) and
Fields!createdonValue.Value <= DateValue(DateAdd("D",-1,DateAdd("D",-(Day(Now)-1),Now))),"Last Month",
Fields!createdonValue.Value >= DateSerial(Year(Now()), 1, 1) and
Fields!createdonValue.Value <= DateSerial(Year(Now()), 12, 31),"Year to Date"
Any help much appreciated
Thanks
Pradnya07Not sure why you want to se IIF as Switch is more compact
Anyways it will look like this
=IIf(
Fields!createdonValue.Value = Now(), "Today",IIf(
Fields!createdonValue.Value = DateAdd("d",-1,Today()),"Yesterday",Iif(
Fields!createdonValue.Value >= FORMATDATETIME(DateAdd(DateInterval.Day, -6,DateAdd(DateInterval.Day, 1-Weekday(today),Today)),DATEFORMAT.ShortDate) and
Fields!createdonValue.Value <= FORMATDATETIME(DateAdd(DateInterval.Day, -0,DateAdd(DateInterval.Day, 1-Weekday(today),Today)),DATEFORMAT.ShortDate),"Last Week",IIf(
Fields!createdonValue.Value >= FORMATDATETIME(DateAdd(DateInterval.Day, -13,DateAdd(DateInterval.Day, 1-Weekday(today),Today)),DATEFORMAT.ShortDate) and
Fields!createdonValue.Value <= FORMATDATETIME(DateAdd(DateInterval.Day, -0,DateAdd(DateInterval.Day, 1-Weekday(today),Today)),DATEFORMAT.ShortDate),"Last Fortnight",IIf(
Fields!createdonValue.Value >= DateValue(DateAdd("M",-1,DateAdd("D",-(Day(Now)-1),Now))) and
Fields!createdonValue.Value <= DateValue(DateAdd("D",-1,DateAdd("D",-(Day(Now)-1),Now))),"Last Month",IIf(
Fields!createdonValue.Value >= DateSerial(Year(Now()), 1, 1) and
Fields!createdonValue.Value <= DateSerial(Year(Now()), 12, 31),"Year to Date")))))
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Use of boolean variables in BPEL switch statements
I have a workflow with a single boolean input parameter:
<element name="input" type="boolean"/>
I wish to use a switch statement within the workflow, based on the value of that boolean parameter.
When I use the following XPath expression:
bpws:getVariableData("input","payload","/tns:BooleanRequest/tns:input")
I get the correct functionality, although I get the following BPEL compiler warning:
" [bpelc] [Warning ORABPEL-10078]: return value of this expression may not be a boolean
[bpelc] [Description]: in line 35 of "C:\eclipse\workspace\Boolean\Boolean.bpel", xpath expression "bpws:getVariableData("input","payload","/tns:BooleanRequest/tns:input")" used in <switch> may not return boolean type value, the xpath engine would automatically try to convert the return value to boolean..
[bpelc] [Potential fix]: Please use one of the built-in boolean functions from xpath http://www.w3.org/TR/xpath#section-Boolean-Functions to convert the return value to boolean.."
However, the boolean functions referenced do not appear to be relevant to a variable which is already of a boolean type. If I attempt to use the boolean() function in my XPath expression, I get rid of the compiler error, but the workflow now does not work as required.
How can I get rid of the compiler warning and still get the required functionality, and/or am I doing the wrong thing?
I am currently running on JBoss, with BPEL release 2.1.2 [build #1226].
Thanks for any help or ideas.Hi Marlon,
Thanks for that - I guess we have to accept the vagaries of XPath and the absence of type-checking for variables.
I hadn't fully understood until I started investigating that I can assign ANY string to variable of type xsd:boolean, which has been the cause of some of the confusion for me - whether that value is then considered true or false depends on how you write your test condition.
I tried with your condition, and it didn't seem to work (evaluated to true if the variable data was the string "true()", but otherwise it seemed to always evaluate to false.
I also tried the following:
condition="bpws:getVariableData('booleanVariable')=true()"
but that evaluates to true for any string of length > 0.
The only one I can get to consistently work is:
condition="bpws:getVariableData('booleanVariable')=string(true())"
although that means that variable data of "TRUE" will evaluate to false (may well be the correct behaviour, depending on how you're setting the boolean variable in the first place). -
Compiler error when useing switch statements in an inner class
I have defined several constants in a class and want to use this constans also in an inner class.
All the constants are defined as private static final int.
All works fine except when useing the switch statement in the inner class. I get the compiler error ""constant expression required". If I change the definition from private static final to protected static final it works, but why?
What's the difference?
Look at an example:
public class Switchtest
private static final int AA = 0;
protected static final int BB = 1;
private static int i = 0;
public Switchtest()
i = 0; // <- OK
switch(i)
case AA: break; //<- OK, funny no problem
case BB: break; //<- OK
default: break;
private class InnerClass
public InnerClass()
i = 0; // <- OK: is accessible
if (AA == i) // <- OK: AA is seen by the inner class; i is also accessible
i = AA + 1;
switch(i)
case AA: break; // <- STRANGE?! Fail: Constant expression required
case BB: break; // <- OK
default: break;
}Thank's a lot for an explanation.Just a though:
Maybe some subclass of Switchtest could decalare its own variable AA that is not final, but it can not declare its own BB because it is visible from the superclass. Therefore the compiler can not know for sure that AA is final. -
Enum class not supported for switch() statement in 12.4 beta?
Hi fellow 12.4 beta testers,
It would appear "enum class" isn't supported for switch() statements in the 12.4 beta. This compiles fine under clang and g++. Will this be fixed for the final release? This currently causes compile errors for us, since __cplusplus >= 201103L evaluates to true, so our code uses "enum class" instead of plain "enum". It looks like the C++11 standard says it should be supported:
Switching on enum class in C++ 0x - Stack Overflow
Many thanks,
Jonathan.
$ cat test.cpp
#include <iostream>
enum class Ternary { KnownFalse = 0, KnownTrue = 1, Unknown = 2 };
int main( void )
Ternary foo;
switch ( foo ) {
case Ternary::KnownTrue:
case Ternary::KnownFalse:
case Ternary::Unknown:
std::cout << "Success\n";
$ clang++ -std=c++11 test.cpp
$ g++ -std=c++11 test.cpp
$ /opt/SolarisStudio12.4-beta_mar14-solaris-x86/bin/CC -std=c++11 test.cpp
"test.cpp", line 8: Error: Cannot use Ternary to initialize integral type.
"test.cpp", line 8: Error: Switch selection expression must be of an integral type.
"test.cpp", line 9: Error: An integer constant expression is required for a case label.
"test.cpp", line 10: Error: An integer constant expression is required for a case label.
"test.cpp", line 11: Error: An integer constant expression is required for a case label.
5 Error(s) detected.Thanks for reporting this problem! I have filed bug 18499900.
BTW, according to the C++11 standard, the code is actually not valid. Section 6.4.2, switch statement, says an implicit conversion to an integral type is required, which is not the case for for a scoped enum (one using the "class enum" syntax). This limitation was raised in the C++ Committee as an issue to be fixed, and the C++14 standard makes the code valid.
As a workaround, or to make the code conform to C++11, you can add casts to int for the enum variable and the enumerators.
Message was edited by: Steve_Clamage
Maybe you are looking for
-
How do you write to a 3D array?
I know this is probably a very simple questions, but for some reason I can not think of how to write to a 3D array. The application that I am going to use this for is that I have multiple graphs with x and y data points, and I want to be able to writ
-
I work for a school division where we needed a script that logs the user on to the servers User folder and Assignment folder. We had one that worked last year on the iBook carts but now our staff have macbooks and the original script no longer fuctio
-
Anyconnect, SCEP for Windows
Cisco Adaptive Security Appliance Software Version 9.0(2) Device Manager Version 7.1(2) I need to set up AnyConnect so that remote users using Windows PCs can easily download/provision the AnyConnect client, enroll using SCEP to get their certificate
-
Search in Mail doesn't show results after Migrating
If I search for a word or an adr. in Mail nothing show up. Unless I've just read the mail. Like that newly read email is the only one being searched in ..? This happened after moving my user account to a new MacPro with Migration Assistant. (first a
-
Why does my iMac using Lion reboot immediately after shutdown?
I shut down every night, and for the past several nights my iMac immediately reboots. The only way to solve this is to press the power switch, but if I do that the iMac doesn't reboot the next morning at the time scheduled in the Energy Saver system