I have two methods, getOption() and driver().
getOption() takes a String from a scanner, breaks it into individual words, and returns an array of Strings.
driver() then gets the first value of that array, getOption()[0], and begins a while loop based on that first String. While the String does not equal "quit", check if the value matches any switch case. However, when I run it, it can do any of the switch cases, but the quit statement never works. Can anyone give me a hand?
public String[] getOption(){
String optionLine[];
Scanner input = new Scanner(System.in);
System.out.println("Input string\n");
String line = input.nextLine();
optionLine = line.split(" ");
return optionLine;
}
public void driver(){
String option = getOption()[0];
Stats s = new Stats(data);
while (!"quit".equals(option)){
switch (option) {
case "add": //data.put(getOption()[1], getValues());
System.out.println("add");
break;
case "set": System.out.println("set");
break;
case "print": System.out.println(Arrays.toString(data));
break;
case "sum": System.out.println(s.sum());
break;
case "mean": System.out.println(s.mean());
break;
case "stdev": System.out.println(s.standardDeviation());
break;
case "median": System.out.println(s.median());
break;
case "primes": System.out.println(s.primes());
break;
case "summary": System.out.println("summary");
break;
//case "test": System.out.println(Arrays.toString(getValues()));
}
driver();
}
}
You are calling recursively at the end of your while loop the method driver();
no matter if you read getOption or not, you are still coming back inside the method...
that is the reason of the apparently not working while condition...
a very unusual pitfall.
Once you get into your While loop, you never change the value of option. You could change your while to be
while (true){
option = getOption()[0];
Stats s = new Stats(data);
switch (option) {
case "add": //data.put(getOption()[1], getValues());
System.out.println("add");
break;
case "set": System.out.println("set");
break;
case "print": System.out.println(Arrays.toString(data));
break;
case "sum": System.out.println(s.sum());
break;
case "mean": System.out.println(s.mean());
break;
case "stdev": System.out.println(s.standardDeviation());
break;
case "median": System.out.println(s.median());
break;
case "primes": System.out.println(s.primes());
break;
case "summary": System.out.println("summary");
break;
//case "test": System.out.println(Arrays.toString(getValues()));
case "quit": break;
}
}
Note, if you use my answer, you will need to no longer recursively call driver().
You don't seem to be changing the value of option anywhere. You're calling driver() recursively, but that doesn't affect the local variable in the currently executing method which stays the same.
So, one driver() method calls another, which creates its own option variable, unrelated to the option variable of the caller. Basically, only the innermost call to driver() will ever return and you'll be stuck in the while loop of its caller.
Get rid of that recursion, it's unnecessary. Under the switch just call getOption() and update the value of option.
while (!"quit".equals(option)){
// switch statement
option = getOption()[0];
}
Related
Hi please in a switch case program that I am developing, I am using a do..while loop to handle the case when a user enters a value that does not meet the condition but got stuck with what I should put in the "while" brackets as an error is shown on the "while" line..
package assignment;
import java.util.*;
public class Assignment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("1)Monday\n2)Tuesday\n3)Wednesday\n4)Thursday\n5)Friday\n6)Saturday\n7)Sunday");
System.out.println("");
int day = input.nextInt();
System.out.println(" ");
do {
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Oh oh, that's not an accepted number, kindly try again");
break;
}
for (int clear = 0; clear < 1000; clear++) {
System.out.println("\b");
}
} while (!(day.equals("1") || day.equals("2") || day.equals("3") || day.equals("4") || day.equals("5") || day.equals("6") || day.equals("7")));
}
}
Instead of checking day as a String, simply check it as an integer which it already is. No need to allocate extra memory when creating a new String to check with an integer.
When you begin your while loop, it seems that there is no way to check for new input. How would you be able to get new input EACH time in your loop?
There is no reliable way to clear your console cross platform as depending on the IDE you are using or which terminal UNIX or PowerShell or CMD. Take a look at this answer Java: Clear the console
Since this seems like a homework assignment, I suggest that you think about how your while loop conditions could be simplified.
Hint: Is there any way to check a range of numbers? What if you had to check 1000 different numbers, would you check each number with OR conditions?
I am working on a program that is a simple game. I'm using a switch statement to return the file location of images that are assigned to buttons. In order to do this I am using a switch statement inside a method called "get Image View" it returns a string that can be fed into an image view that I will need to compare the image in the button to another image elsewhere. I think I may be over-explaining, anyway. my IDE (NetBeans) is telling me that my break statement is unreachable and I can not figure out why. I have used a switch statement that looks very similar to mine and there is an example in my textbook that is also very similar. I know that I still need to have a default return statement I just want to know what's up with my break statements. Thank you in advance!
public String getImageView(int button)
{
switch(button)
{
case 0: System.out.println("error");
case 1: return "1.png";
break;
case 2: return "2.png";
break;
case 3: return "3.png";
break;
case 4: return "4.png";
break;
case 5: return "5.png";
break;
case 6: return "6.png";
break;
case 7: return "7.png";
break;
case 8: return "8.png";
case 9: return "9.png";
case 10: return "10.png";
}
}
You can try something like below :
public String getImageView(int button){
String imageViewName = "";
switch(button)
{
case 0: System.out.println("error");
case 1: imageViewName = "1.png";
break;
case 2: imageViewName = "2.png";
break;
case 3: imageViewName = "3.png";
break;
case 4: imageViewName = "4.png";
break;
case 5: imageViewName = "5.png";
break;
case 6: imageViewName = "6.png";
break;
case 7: imageViewName = "7.png";
break;
case 8: imageViewName = "8.png";
break;
case 9: imageViewName = "9.png";
break;
case 10: imageViewName = "10.png";
break;
}
return imageViewName;
}
Hope this helps.
Well switch-state-statements behaves not like a big if-else-statement.
Consider this code:
int a = 0;
switch (a) {
case 0:
//do something
break;
case 1:
//do something else
break;
default:
//default case
}
Here the first case will be triggered as you can tell by the value of a.
If you want to first case be executed but also want to slip in the second case anyway you can omit the break in the first case.
So this code:
int a = 0;
switch (a) {
case 0:
System.out.println("case 0");
case 1:
System.out.println("case 1");
break;
default:
//default case
}
will output:
case 0
case 1
just like it is in your Code.
So maybe you should consider the break; in your first case. Otherwise it will execute the println but also returning 1.png.
In the below code containing the switch statements, is it possible to incorporate the equalsIgnoreCase method, i.e., user gets grade message whether or not a or A is entered, etc. etc.?
I managed to get the right result by using "convert user input to upper case" method, but I was curious whether the ignoreCase method can be used here. I tried to do it, but it does not seem to work in any way, possibly because ignoreCase is a Boolean which returns true/false result, not a message. I tried researching this, but all online results suggest using toUpperCase method, something I already tried and worked.
Scanner scan = new Scanner(System.in);
System.out.println("Please enter grade.");
String gradeLetter = scan.next();
String message = "A";
switch (gradeLetter) {
case "A":
message = "Excellent!";
break;
case "B":
message = "Good job.";
break;
case "C":
message = "You passed.";
break;
case "D":
message = "You can do better.";
break;
case "F":
message = "You failed.";
break;
default: message = gradeLetter + " is invalid.";
}
System.out.println(message);
You could switch (gradeLetter.toUpperCase()) but this looks like a better use case for Map<String, String> to me. Something like
Scanner scan = new Scanner(System.in);
Map<String, String> map = new HashMap<>();
map.put("A", "Excellent!");
map.put("B", "Good job.");
map.put("C", "You passed");
map.put("D", "You can do better.");
map.put("F", "You failed.");
// ... No Loop?
System.out.println("Please enter grade.");
String gradeLetter = scan.next();
System.out.println(map.getOrDefault(gradeLetter.toUpperCase(),
String.format("%s is invalid.", gradeLetter)));
As you already mentioned, you can switch on gradeLetter.toUpperCase().
You can also use fall-through, where multiple case labels jump to the same block of code:
switch (gradeLetter) {
case "A":
case "a":
message = "Excellent!";
break;
case "B":
case "b":
message = "Good job.";
break;
/* etc */
Consider, for example, "a" and "A". There is no break statement after case "A":, so execution continues straight into the case "a": block.
Beginner here, please be as explanatory as possible!
A course question asked me to create a menu (done).
Have multiple option on the menu give different one-time result (done).
Now it wants me to implement a for, while and do...while loop (CANNOT UNDERSTAND)
I have genuinely tried all of my rudimentary knowledge, including creating and populating an array inside the for loop (which in hindsight was a stupid idea).
public void displayMenu()
{
System.out.println("A. Option #A");
System.out.println("B. Option #B");
System.out.println("C. Option #C");
System.out.println("D. Option #D");
System.out.println("X. Exit!");
System.out.println();
System.out.println("Please enter your choice:");
}
public void start()
{
displayMenu();
Scanner console = new Scanner(System.in);
String input = console.nextLine().toUpperCase();
System.out.println();
switch (input)
{
case "A": System.out.println("Option #A was selected"); break;
case "B": System.out.println("Option #B was selected"); break;
case "C": System.out.println("Option #C was selected"); break;
case "D": System.out.println("Option #D was selected"); break;
case "X": System.out.println("You chose to Exit"); break;
default: System.out.println("Invalid selection made"); break;
}
}
public void startFor()
{
/*Each of these methods will modify the original start() method, each
*will add a loop of the specific type so that the menu is displayed
*repeatedly, until the last option is selected. When the last option
*is selected, exit the method (i.e. stop the loop).
*/
}
As you asked for an example with for in the comments.
The point of the exercise seems to be to iterate on the menu until an exit condition is met ("X".equals(input)). That means than between the three conditions in the for statement, that's the only one you need to specify. This is because the general form of a (basic) for statement is
for ( [ForInit] ; [Expression] ; [ForUpdate] )
Where none of those terms between brackets are mandatory, so we can as well get rid of [ForInit] and [ForUpdate] (but keeping the semicolons). This has the effect of not initializing anything with [ForInit] and doing nothing at the end of each iteration of the loop with [ForUpdate], leaving us only checking for the exit condition that is given by the [Expression] expression (when it's evaluated to false, the loop exits).
Notice that the console is declared outside the loop, since it would be wasteful to allocate one at each iteration. And also input, since you need it in the for statement's condition.
Scanner console = new Scanner(System.in);
String input = "";
for (;!"X".equals(input);) { // notice, the first and last part of the for loop are absent
displayMenu();
input = console.nextLine().toUpperCase();
System.out.println();
switch (input) {
case "A": System.out.println("Option #A was selected"); break;
case "B": System.out.println("Option #B was selected"); break;
case "C": System.out.println("Option #C was selected"); break;
case "D": System.out.println("Option #D was selected"); break;
case "X": System.out.println("You chose to Exit"); break;
default: System.out.println("Invalid selection made"); break;
}
}
You may notice this is a bit awkward, as this is not what you usually use a for loop for.
Anyway, at this point, the while version becomes trivial (while (!"X".equals(input))) and, in this case, the do...while is equivalent as well, (do { ... } while (!"X".equals(input))) as the same condition applies both at the end of the current loop and at the beginning of the next one, and there are no side effects between them.
As an aside, you may notice that while (condition) and for (; condition ;) are functionally equivalent and you may wander why you should use one instead of the other. The answer is readability. It's a lot more clear what you want to do when you do while (condition).
All arguments in for loop is not mandatory.
Define a stopflag and check whether is input is "X" or not.
Whenever input is "X" just change stopFlag or just simply you can break loop using break statement;
public void startFor()
{
boolean stopFlag = false;
for(; stopFlag == false ;) {
displayMenu();
Scanner console = new Scanner(System.in);
String input = console.nextLine().toUpperCase();
System.out.println();
switch (input)
{
case "A": System.out.println("Option #A was selected"); break;
case "B": System.out.println("Option #B was selected"); break;
case "C": System.out.println("Option #C was selected"); break;
case "D": System.out.println("Option #D was selected"); break;
case "X": System.out.println("You chose to Exit"); break;
default: System.out.println("Invalid selection made"); break;
}
if(input.contentEquals("X"))
stopFlag = true;
}
}
I am expecting my input to be one of three groups of chars and need to decide what to do with it based on which group it falls in. I'm trying to figure out how to define a switch with multiple cases to do this. Here is what I have so far:
while(in.hasNextChar())
{
char test = in.nextChar();
List<Signal> out = new List<Signal>(0);
switch(test)
{
case '1','0','x','X':
out.add(fromString(test));
break;
case ' ','/t':
break;
default:
throw new ExceptionLogicMalformedSignal;
}
}
return out;
}
You have the syntax wrong. You need to take advantage of fall-through:
switch(test) {
case '1':
case '0':
case 'x':
case 'X':
out.add(fromString(test));
break;
case ' ':
case '\t':
break;
default:
throw new ExceptionLogicMalformedSignal;
}
A case is just a label, very similar to what you'd use with a goto (which is essentially what is happening behind the scenes). It's not a statement, since it does nothing itself — it just names an address. So if test is '0', it can happily continue through the 'x' and 'X' cases to reach the actual statement code since there's not anything being done by those labels. Only break "ends" a case.
You can actually insert code between cases even without a break:
switch(test) {
case '1':
System.out.println("This is printed by case '1'");
case '0':
System.out.println("This is printed by both case '1' and case '0'");
break;
case 'x':
case 'X':
System.out.println("This is only printed by the Xs");
break;
default:
break;
}