orphaned case error in a switch statments - java

i wrote a small program in java
the user enter a number to get his multiplication table
and then type the maximum length of that table
but in the third case (case r) i got an error orphaned case
and it seems clean code to me
public class JavaApplication2 {
public static void main(String[] args) throws IOException
{
System.out.println("Multiplication Table v1.0");
System.out.println("Developped By Roy Jalbout");
System.out.println("-------------------------");
System.out.println("Type 'E' To Quit The Program\nType 'H' To Read The Help File\nType 'R' To Run The Program");
char act = (char)System.in.read();
switch (act) {
case 'e':
case 'E':
System.exit(0);
break;
case 'h':
case 'H':
System.out.println("The Multiplication Table Version 1.0 Developped By Roy Jalbout is A Simple Program All you have to do is to choose the number that you want to get his multiplication table and then choose the maximum lenght of that table");
System.out.println("----------------------------------");
System.out.println("Type back to go to the main thread");
String mainthread = scn.next();
if ("back".equals(mainthread)){
JavaApplication2.main(args);
break;
case 'r':
case 'R':
Scanner scn = new Scanner(System.in);
System.out.print("Enter A Number To Get His Multiplication Table : ");
int num = scn.nextInt();
System.out.print("Enter The Max Number Of The Multiplication Table : ");
int max = scn.nextInt();
int b=1;
while (b<=max){
System.out.println(num + " * " + b + " = " + b*num);
b++;
JavaApplication2.main(args);
}
default:
System.out.println(act + " is an Invalid Choice");
}
}
}
}
any help???

if ("back".equals(mainthread)){
JavaApplication2.main(args);// you are not closing the brace here..
break;

The problem with the orphaned case, for me, was there was a couple of not closed curly brackets after I began the switch case.
For example, there was a loop inside a case which I had not closed.
Once I closed there was no obstacles

Related

java while loop with if/else statement, else argument runs forever instead of restarting while loop

So I have an assignment where I am supposed to prompt the user to enter an arithmetic operator, and then 2 numbers, and produce the result; i.e. user enters /, 20, 2 and the OUTPUT should be 10. I am using checks to ensure the proper value types are entered by the user, and my check for the integers entered runs forever if the else statement is activated. I am not sure where I am going wrong here. any guidance would be greatly appreciated.
import java.util.Scanner;
public class mainClass {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean charCheck = true; //for verifying user arithmetic input
boolean numCheck = true; //for verifying user int input
boolean sysCheck = true; //for program outer while loop
int n1 = -1; //user entered number 1
int n2 = -2; //user entered number 2
char x = ' '; //user entered arithmetic operator
while (sysCheck == true)
{
while (charCheck == true)
{
System.out.println("Please enter either +, -, *, /to proceed. Enter x to end the program");
x = input.next().charAt(0);
switch(x) //check input validity for x before the program proceeds
{
case '+':
case '-':
case '*':
case '/':
System.out.println(x);
charCheck = false;
break;
case 'x':
System.exit(0);
break;
default:
System.out.print("That is an invalid entry. ");
}
}
System.out.println("Now, please enter 2 numbers, seperated by a space: ");
while(numCheck)
{
if(input.hasNextInt())
{
n1 = input.nextInt();
n2 = input.nextInt();
System.out.println(n1 + " " + n2);
numCheck = false;
}
else
System.out.print("That is an invalid entry. ");
}
switch(x) //check input validity for x before the program proceeds
{
case '+':
System.out.print("The result is: " + (n1 + n2));
break;
case '-':
System.out.print("The result is: " + (n1 - n2));
break;
case '*':
System.out.print("The result is: " + (n1 * n2));
break;
case '/':
System.out.print("The result is: " + (n1 / n2));
break;
}
}
}
}
After playing around with the code more and researching more, I found the solution. the issue I was having was due to not including the line
input.next(); in my else statement (input is the name of my scanner, if you named your scanner something else, that name would be in it's place)
while(numCheck)
{
System.out.println("Now, please enter 2 numbers, seperated by a space: ");
if(!input.hasNextInt())
{
System.out.println("That is an invalid entry. ");
input.next();
}
else
{
n1 = input.nextInt();
n2 = input.nextInt();
numCheck = false;
}
}

JAVA: NoSuchElementException while function executing second time

I'm working on simple Calculator app on Java. When user enter 0(which returns info no math operator), i want to restart my function. But when I do it throws NoSuchElementException when debug pointer comes to int operationInput = sc.nextInt(); Here is the my whole code block. I tried try catch but it stucks. Maybe it cannot re-identify a variable because it doesn't quit of that code block.
static Object mathOperators() {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a number for choosing operation(if you don't know what operation equals to which number click 0): ");
int operationInput = sc.nextInt();
sc.close();
switch (operationInput) {
case 0:
System.out.println("1: Addition - 2: Subtraction - 3: Multiplication \n"
+ "4: Division - 5: Modulus");
return mathOperators();
case 1:
System.out.println(additionCalc());
break;
case 2:
System.out.println(substractionCalc());
break;
case 3:
System.out.println(multiplyCalc());
break;
case 4:
System.out.println(divisionCalc());
break;
case 5:
System.out.println(modulusCalc());
break;
default:
System.out.println("Please enter a valid number");
break;
}
return 0;
}
You can use only one Scanner(System.in) in your app. You must close the scanner before calling "break" in your switch cases.

How to ignore lettercase? [duplicate]

This question already has answers here:
Case insensitive matching in Java switch-case statement
(5 answers)
Closed 2 years ago.
So, I'm trying to make a simple menu with switches.
I have a letter choice inside it. I'm using next().charAt(0); to scan a letter.
It worked well, but I want to simplify it. you see, I have to make a case each choice both uppercase and lowercase.
So how to ignore case so I don't have to make both cases?
Also note: I'm using the old version of Java and Netbeans 8.2 as my IDE. (because my college keeps insisting not to use the newer one. Probably because they don't have the textbook yet.), so probably newer syntax wouldn't work.
my code:
import java.util.Scanner;
public class NewClass2 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
char milk;
int s, h, price;
h = 0;
price = 0;
String type, size;
System.out.println("NutMart");
System.out.println("Milk selections:\n A. Milk A \n\t 1. Regular ($10) \n\t 2. Medium ($20) \n\t 3. Large ($30)");
System.out.println(" B. Milk B \n\t 1. Regular ($15) \n\t 2. Medium ($30) \n\t 3. Large ($45)");
System.out.println(" C. Milk C \n\t 1. Regular ($20) \n\t 2. Medium ($40) \n\t 3. Large ($60)");
System.out.println("Insert Milk Type: ");
milk = input.next().charAt(0);
switch(milk){
case 'a':
type = "Milk A";
h = 10;
break;
case 'b':
type = "Milk B";
h = 15;
break;
case 'c':
type = "Milk C";
h = 20;
break;
case 'A':
type = "Milk A";
h = 10;
break;
case 'B':
type = "Milk B";
h = 15;
break;
case 'C':
type = "Milk C";
h = 20;
break;
default:
System.out.println("Invalid!");
System.out.println("Please select the correct choice: ");
milk = input.next().charAt(0);
break;
}
System.out.println("Select the size: ");
while (!input .hasNextInt()) input .next();
s = input.nextInt();
switch(s){
case 1:
size = "Regular";
price = h * 1;
break;
case 2:
size = "Medium";
price = h * 2;
break;
case 3:
size = "Large";
price = h * 3;
break;
default:
System.out.println("Invalid");
System.out.println("Please select the correct choice: ");
while (!input .hasNextInt()) input .next();
s = input.nextInt();
break;
}
System.out.println("Individual Price: $" + price);
System.out.println("Please insert the quantity: ");
while (!input .hasNextInt()) input .next();
int quantity = input.nextInt();
int total = price * quantity;
System.out.println("Your total will be $" + total );
}
}
Note, that in this case converting to a consistent case is the best was to achieve your goal. But when you have a variety of results for dissimilar inputs in a switch statement you can do the following for case constructs.
case 'a':
case 'A:
type = "Milk A";
h = 10;
break;
...
The case will simply fall thru whether 'a' or 'A' was provided.

query about switch function in java

Scanner input = new Scanner(System.in);
System.out.println("please choose the operator");
System.out.println("1-->+ \n2-->- \n3-->* \n4-->/");
int z = input.nextInt();
switch (z) {
case 1:
System.out.println("your result is" + (x + y));
break;
case 2:
System.out.println("your result is" + (x - y));
break;
case 3:
System.out.println("your result is" + (x * y));
break;
case 4:
System.out.println("your result is" + (x / y));
break;
default:
System.out.println("choose the option from listed above");
break;
}
above code is for calculator in switch...
query is :
how can i call the switch function again in default case ?
Well, you can't execute the switch statement again because that does not solve the problem. z's value does not change, so it will always go to the default branch no matter how many times you re-execute the switch.
I suggest to put the whole thing in a loop and break out of the loop for cases 1-4.
loop:
while (true) {
Scanner input=new Scanner(System.in);
System.out.println("please choose the operator");
System.out.println("1-->+ \n2-->- \n3-->* \n4-->/");
int z=input.nextInt();
switch(z)
{
case 1 :
System.out.println("your result is"+(x+ y));
break loop;
case 2 :
System.out.println("your result is"+(x- y));
break loop;
case 3 :
System.out.println("your result is"+(x* y));
break loop;
case 4 :
System.out.println("your result is"+(x/ y));
break loop;
default :
System.out.println("choose the option from listed above");
break;
}
}
Note that I wrote break loop instead of break. break will just break out of the switch statement. This is why I added a label loop: before the loop starts, so that I can break out of the loop, instead of the switch, later.
Some corrections of your terminology
In Java, there are technically no functions. Functions must be outside of a class. There are only "methods" in Java. They look like this:
public static void someMethod(int somePar) { }
switch is neither a function nor a method, so you can't "call" it. switch is a control structure that is "executed" or "run".
You can do like this:
public void promptUser(){
Scanner input=new Scanner(System.in);
boolean validOption = false;
while(!validOption){
validOption = true;
System.out.println("please choose the operator");
System.out.println("1-->+ \n2-->- \n3-->* \n4-->/");
int z=input.nextInt();
switch(z){
case 1 :
System.out.println("your result is"+(x+ y));
break;
case 2 :
System.out.println("your result is"+(x- y));
break;
case 3 :
System.out.println("your result is"+(x* y));
break;
case 4 :
System.out.println("your result is"+(x/ y));
break;
default :
System.out.println("choose the option from listed above");
validOption = false;
break;
}
}
}
I prefer using a loop so you won't be stacking a lot of calls to the same method over and over, thus you can avoid OutOfMemoryError.
Let's assume your code is in a function called calculate()
There are a few ways you could do this.
Recursively:
Just call the function again in the switch.
default :
System.out.println("choose the option from listed above");
calculate();
return;
Return a value and loop:
Change the function so it returns a value. For example, return true if is does anything but default, and false if it hits default. Then, in the logic that calls calculate(), put it in some sort of loop.
bool doLoop = true;
while (doLoop)
{
doLoop = !calculate()
}
You could put it inside a loop, for example a do ... while loop, and you may capture a key as ending condition.
do {
// your code here
} while(ending_condition);
while(true)
{
Scanner input=new Scanner(System.in);
System.out.println("please choose the operator");
System.out.println("1-->+ \n2-->- \n3-->* \n4-->/ \n5-->Exit");
int z=input.nextInt();
switch(z)
{
case 1 :
System.out.println("your result is"+(x+ y));
break;
case 2 :
System.out.println("your result is"+(x- y));
break;
case 3 :
System.out.println("your result is"+(x* y));
break;
case 4 :
System.out.println("your result is"+(x/ y));
break;
case 5 :
System.exit(0);
default :
System.out.println("choose the option from listed above");
break;
}
}

System.in.read is causing loop to execute thrice

import java.io.IOException;
import java.io.InputStreamReader;
public class doSwitch {
public static void main(String[] args) throws IOException {
char choice;
do {
System.out.println("Welcome User");
System.out.println("1. Change plan");
System.out.println("2. Pay Bill");
System.out.println("3. Complaints");
System.out.println("4. De-activate account");
System.out.println("Choose one the above option");
choice = (char) System.in.read();
} while (choice < '1' || choice > '4');
System.out.println("User's Choice:" + choice);
///////////////////////////// switch
///////////////////////////// case////////////////////////////////////
switch (choice) {
case '1':
System.out.println("There are different plans than you can opt for");
break;
case '2':
System.out.println("Pay bill using credit card or debit card");
break;
case '3':
System.out.println("In case of complaint call 121");
break;
case '4':
System.out.println("Are you sure you want to discontinue with us");
break;
}
}
}
This codes works properly if i entered values between 1 to 4. But If the value is greater than 4 then its executing the loop 3 times. I figured out its taking the value \n, \r. What i m not getting is how can i avoid it. and why it works for values 1-4
try
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
System.in.read() reads a single byte. In your case it reads the actual inputed character. If the character doesn't equal 1-4, then the loop continues and the next byte will be read, which will be a return character. The scanner objects takes care of this for you.

Categories

Resources