Print inside Switch - java

Desired outcome is printing "i is zero" then one, two, three, four..
It seems like my for loop is working properly, i is getting to 5 every time I execute but none of my cases are true, so nothing is printing. What am I doing wrong?
public class SwitchTest {
public static void main(String[] args) {
int i;
for ( i=0; i < 5; i++); {
switch (i) {
case 0:
System.out.println("i is zero");
case 1:
System.out.println("i is one");
case 2:
System.out.println("i is two");
case 3:
System.out.println("i is three");
case 4:
System.out.println("i is four");
}
}
}
}

You need to add break statement after every Sysout like.
switch (i) {
case 0:
System.out.println("i is zero");
break;
case 1:
System.out.println("i is one");
break;
case 2:
System.out.println("i is two");
break;
case 3:
System.out.println("i is three");
break;
case 4:
System.out.println("i is four");
break;
default:
//some statement here.
}

Nothing gets printed because there's a semicolon after your for statement, and java doesn't complain because it's still valid syntax. But fix it and you'll find that all of your cases print out on every iteration. This is because a switch statement will execute from the relevant case, all the way to the bottom, unless you end each case statement by a break:
switch (i) {
case 0:
System.out.println("i is zero");
break; //"break" means "exit the switch block here, don't go any further"
case 1:
System.out.println("i is one");
break;
case 2:
System.out.println("i is two");
break;
case 3:
System.out.println("i is three");
break;
case 4:
System.out.println("i is four");
break; //This one is optional
}
For good style, you should also include a default case, but that's a story for another day...

Related

How to combine user input into a score system (JFrame)

I am trying to make a proper marking system for my multiple choice quiz, but when I answer the quiz, only the default in my switch statement will appear, How can I put in the input?
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
int mark = 0;
switch (mark) {
case 5:
JOptionPane.showMessageDialog(null, "D");
break;
case 6:
JOptionPane.showMessageDialog(null, "C");
break;
case 7:
JOptionPane.showMessageDialog(null, "B");
break;
case 8:
JOptionPane.showMessageDialog(null, "A-");
break;
case 9:
JOptionPane.showMessageDialog(null, "A");
break;
case 10:
JOptionPane.showMessageDialog(null, "A+");
break;
default:
JOptionPane.showMessageDialog(null, "F");
break;
}
Please check the value of mark. It is 0 hence default is showing.
Please check.
Please put break; statement in all case like.
case 6:
JOptionPane.showMessageDialog(null, "C");
break;
You must use a break; after each statement, otherwise the rest will be evaluated and the last will count.
Here's an example taken from here:
switch(expression) {
case value :
// Statements
break;
case value :
// Statements
break;
// You can have any number of case statements.
default : // Optional
// Statements
}

Can we have label inside switch case java [duplicate]

This question already has answers here:
Break label in switch
(3 answers)
Closed 6 years ago.
I have below pseudocode code with switch block with 4 cases. In 4th case I have if else conditions and when some condition satisfies, I am reducing list size by 1 and it has to come back to case 4 again and execute from the beginning of the 4th case. I tried to create a label in case 4: but it is giving the compilation error.
switch(choice) {
case 1: /* do operations */
break;
case 2: /* do operations */
break;
case 3: /* do operations */
break;
case 4:
mylabel:
if(condition1) {
}
else if(condition2) {
}
else {
break mylabel;
}
break;
default :
}
Above code gives the compilation error. But I want the program flow to be something like that. So I tried below code:
switch(choice) {
case 1: /* do operations */
break;
case 2: /* do operations */
break;
case 3: /* do operations */
break;
case 4:
if(condition1) {
}
else if(condition2) {
}
else {
break case 4;
}
break;
default :
}
With above code still, I am facing compilation issues. Is there any alternative for achieving the same. Here I need to go back to the beginning of the same case statement from where I will break. Hence it is different.
use label and while loop. it will work
switch (choice) {
case 1: /* do operations */
break;
case 2: /* do operations */
break;
case 3: /* do operations */
break;
case 4:
mylabel:{
while(true){
if(condition1) {
}else if(condition2) {
}else {
break mylabel;// breaks the while-loop
}
}
}
default:
break;
}
public void switchFunction(String choice){
switch(choice) {
case 1:
do1();
break;
case 2: /* do operations */
break;
case 3: /* do operations */
break;
case 4:
recursiveFunction();
break;
default :
}
}
public void recursiveFunction(){
if(condition1){
doSomething();
}
else if(condition2){
doSomethingElse();
}
else{
/* You can call it as much as you want! */
recursiveFunction();
}
}

Modification of value in switch case

public class Sample {
public static void main(String[] args) {
int i = 9;
switch (i) {
default:
System.out.println("default");
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
case 2:
System.out.println("two");
}
}
}
Output:
default
zero
Although i was initialized as 9, how is it possible that case 0 was picked? What is the reason?
You miss a break statement after the first default case so the excution just falls through to the second case.Also put the Default case last so that it is only excuted after all the other cases are checked.
public static void main(String[] args) {
int i = 9;
switch (i) {
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
default:
System.out.println("default");
break;
}
}
When I ran this, it printed:
default
zero
You have a couple things wrong.
(1) Put the default case at the end, not beginning. Otherwise you'll automatically go into the default case.
(2) Put a break statement after each case. If you don't, you code will continue from the case without the break and execute the code from the next case (and the next) until it reaches a break.
Try this
public class Sample {
public static void main(String[] args) {
int i = 9;
switch (i) {
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
default:
System.out.println("default");
}
}
}
Link on Java switch statements --http://www.tutorialspoint.com/java/switch_statement_in_java.htm.
You missed using break in your default case thus the program continues to execution and prints "zero".
You are doing two mistakes.
you should place the default case always at the end
you are missing important breaks
Solution:
public class Sample
{
public static void main(String[] args)
{
int i = 9;
switch (i)
{
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
default:
System.out.println("default");
}
}
}

Adding Elements in to a queue individually from text file

I would like to add a name to a queue (linked), one name at a time from a text file. If the user selects choice 1 then it should take the next name in from the lists.
Case 1 is not letting me input another choice if I want to add another name.
int choice = console.nextInt();
FileReader names = new FileReader("Customer.txt");
Scanner lookup = new Scanner(names);
Queue a = new Queue();
String customerName;
// This loop was just to verify that
while(lookup.hasNextLine() ){ // It was actually reading
customerName = lookup.next();
System.out.println(customerName);
}
while(true){
switch(choice){
case 1:
customerName = lookup.next();//For some reason its not giving me
a.enqueue(customerName); // The choice to enter another number
break; //even though I made the case while(true)
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
System.out.println(" Exiting......");
break;
default:
continue;
}
break;
}
The problem here is that there is a break after the switch statement. This is causing your code to jump out of the while loop after one pass of the switch statement.
The solution is to remove the break, as such:
while(true){
switch(choice){
case 1:
customerName = lookup.next();//For some reason its not giving me
a.enqueue(customerName); // The choice to enter another number
break; //even though I made the case while(true)
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
System.out.println(" Exiting......");
break;
default:
continue;
}
}

Simple switch in "for" loop and toLowerCase() method

I am very much a beginner in Java. I am making a simple switch, in which the user is entering a number in words. For training I added a "for" loop.
package JavaExc;
import java.util.Scanner;
public class JavaStart {
public static void main(String[] args) {
Scanner sck = new Scanner(System.in);
System.out.println("Type loop counter ");
int counter = sck.nextInt();
System.out.println("Counter is: " + counter );
for (int i = 0; i <= counter; i++) {
System.out.println("Type number in words");
String ch = sck.nextLine();
switch (ch.toLowerCase()) {
case "one":
System.out.println("CHOICE 1");
break;
case "Two":
System.out.println("CHOICE 2");
break;
case "THREE":
System.out.println("CHOICE 3");
break;
case "FoUr":
System.out.println("CHOICE 4");
break;
case "fiVE":
System.out.println("CHOICE 5");
break;
default:
System.out.println("Wrong Data");
break;
}
System.out.println("Loops left:\n " + counter--);
}
System.out.println("End of Switch");
}
}
Here is the result:
Type loop counter
5
Counter is: 5
Type number in words
Wrong Data // ??
Loops left:
5
Type number in words
one
CHOICE 1
Loops left:
4
Type number in words
three // Should be ok, so what is wrong here?
Wrong Data
Loops left:
3
End of Switch //To early break loop I think
Process finished with exit code 0
My questions are: Why first loop make default code? Should I make 2 Scanners? One for take value for counter and second for switch?
Why counter and numbers in words do not working properly?
I know I can do it with tables etc. but generally, the purpose of this program is to test the "toLowerCase()" method.
You're checking your string in lower case ("three") against upper case ("THREE"). Make sure they're both identical and it shouldn't fail.
Switch statement
In your switch clause, you are testing a String that has been turned into a lowercase form of itself. Therefore, the only possible case clause that will be matched is "one", as the others all contain uppercase characters.
Change all of the case clauses to lowercase and it will work, as long as you input the data correctly.
case "one":
System.out.println("CHOICE 1");
break;
case "two":
System.out.println("CHOICE 2");
break;
case "three":
System.out.println("CHOICE 3");
break;
case "four":
System.out.println("CHOICE 4");
break;
case "five":
System.out.println("CHOICE 5");
break;
Not accepting input
Regarding your problem with the program not accepting input, you have to call sck.nextLine() after calling sck.nextInt(), see here for details on why this is.
Only one scanner is necessary.
The convention of a switch statement is similar to an if-else if-else chain. The value placed between the switch statement's parenthesizes is evaluated against every case present in the switch statement.
A switch statement of:
String condition = "foo";
switch(condition){
case "example":{
}
case "foo":{
}
case "bar":{
}
default:{
}
}
is similar to the expression:
if(condition.equals("example")){
}else if(condition.equals("foo")){
}else if(condition.equals("bar")){
}else{
}
Note that by making your input into the switch statement lowercase, it will never match any case that is uppercase.
e.g:
if("tHREE".toLowerCase().equals("tHREE")){
will never evaluate true, since "tHREE" is first being dropped to all lowercase "three" before performing a case-sensitive comparison to "tHREE".
Why first loop make default code?
As explained in Skipping nextLine() after use next(), nextInt() or other nextFoo() methods, nextInt doesn't consume the newline character. Add a call to sck.nextLine(); after setting counter.
Should I make 2 Scanners? One for take value for counter and second for switch?
No, only one Scanner is necessary.
Why counter and numbers in words do not working properly?
First, your for loop condition is i <= counter, which means that it's set up to run counter + 1 times. Change it to i < counter.
Second, your switch cases except for "one" contain capital letters, so they will never match ch.toLowerCase(). Change your case labels to strings with all lowercase letters.
Third, you decrement counter at the end of the for loop, cutting down on the number of iterations run. Instead, use the expression (counter - i - 1) to output the number of loops left.
retype the cases to:
case "one":
System.out.println("CHOICE 1");
break;
case "two":
System.out.println("CHOICE 2");
break;
case "three":
System.out.println("CHOICE 3");
break;
case "four":
System.out.println("CHOICE 4");
break;
case "five":
System.out.println("CHOICE 5");
break;
Ok i added changes and it works fine. Now I will try to make possibilty to input words whatever they are upper or lower cases. Thanks for help! StackOverflow rocks so much!
package JavaExc;
import java.util.Scanner;
public class JavaStart {
public static void main(String[] args) {
Scanner sck = new Scanner(System.in);
System.out.println("Type loop counter ");
int counter = sck.nextInt();
sck.nextLine();
System.out.println("Counter is: " + counter );
int i;
for ( i = 0; i < counter; i++) {
System.out.println("Type number in words");
String ch = sck.nextLine();
switch (ch.toLowerCase()) {
case "one":
System.out.println("CHOICE 1");
break;
case "two":
System.out.println("CHOICE 2");
break;
case "three":
System.out.println("CHOICE 3");
break;
case "four":
System.out.println("CHOICE 4");
break;
case "five":
System.out.println("CHOICE 5");
break;
default:
System.out.println("Wrong Data");
break;
}
System.out.println("Loops left:\n " + (counter - i - 1) );
}
System.out.println("End of Switch");
}}

Categories