query about switch function in java - 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;
}
}

Related

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 can I not repeat the same case after I use it

So, I made a burger class with a method for extra stuff, my question is how can I use case 0,1,2 only 1 time, like if I use case 0, I can't use it anymore, I can use only 1 and 2, If I use case 1 after 0 , then I can use only case 2 since I used case 0 and 1 before , It's possible to do something like that ? If yes how ?
The code:
boolean flag=true;
while(flag){
System.out.println("Enter your choice for extra toppings ");
int choice=scanner.nextInt();
scanner.nextLine();
switch(choice) {
case 0:
double salad = 0.35;
setAdditional(getAdditional() + salad);
System.out.println("salad added\n");
break;
case 1:
double bacon=1.05;
setAdditional(getAdditional()+bacon);
System.out.println("Bacon added \n");
break;
case 2:
double fries=0.79;
setAdditional(getAdditional()+fries);
System.out.println("fries added \n");
break;
case 3:
System.out.println("Done");
flag=false;
}
}
} ```
boolean flag = true;
Set<Integer> set = new HashSet<>();
while (flag) {
System.out.println("Enter your choice for extra toppings ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 0:
if (!set.contains(choice)) {
double salad = 0.35;
setAdditional(getAdditional() + salad);
System.out.println("salad added\n");
break;
}
else {
System.out.println("Added already");
}
continue;
case 1:
double bacon = 1.05;
setAdditional(getAdditional() + bacon);
System.out.println("Bacon added \n");
break;
case 2:
double fries = 0.79;
setAdditional(getAdditional() + fries);
System.out.println("fries added \n");
break;
case 3:
System.out.println("Done");
flag = false;
}
set.add(choice);
}
}
so I did it with Set in the end, only for salad, but it's the same for the rest, if someone else needs it.
your cases go by integer numbers, so an array of boolean with 1 element for every option.
boolean[] allowed = new boolean[options]; (faster than hasMap of string to boolean).
add a check just before the "switch" statement:
if(allowed[choice] && choice != 3) {...}
you should also create an integer constant STOP_OPTION or something like that and use it in the above if-statement and in the final "case" of your switch statement. in your example, set it to 3. then later you can change it without replacing all instances of "3" in your code. but that's more of a styling suggestion.
the "flag" boolean is also redundant, the while loop can just check if choice != 3. be careful of NumberFormatExceptions!
good luck!

How to create a program that converts binary to decimal

I'm trying to convert binary to decimal, how do I change my code to be able to do that? Where did I mess up?
i tried looking at other examples, looking at java api and watching videos but i still can't figure out what mistake i have made.
package Calculator;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("(2) Convert binary to decimal");
System.out.println("\n\n Please enter your choice: ");
int choice = scan.nextInt();
if(choice == 2){
scan.nextLine();
//prompt for user input
System.out.println("Please enter a binary number: ");
String binary = scan.nextLine();
char[] binaryArray = binary.toCharArray();
int i=1;
int integer=0;
//potential problem somewhere around here?
while(i<8){
if(binaryArray[i]==0) {
++i;
}else if(binaryArray[i]==1) {
switch(i) {
case 1:
integer+=128;
++i;
break;
case 2:
integer+=64;
++i;
break;
case 3:
integer+=32;
++i;
break;
case 4:
integer+=16;
++i;
break;
case 5:
integer+=8;
++i;
break;
case 6:
integer+=4;
++i;
break;
case 7:
integer+=2;
++i;
break;
case 8:
integer+=1;
++i;
break;
}
}
}
System.out.println("The decimal value of the binary number is: "+ integer);
scan.close();
}
}
}
The input is always 0. I've tried 11010110, 11111111,and 01010111. Always 0. I know the problem lies somewhere with my integer value not changing but I can't figure out what it specifically is.
This is happening because you are reading the input, and converting into an array of char.
Anywhere where you are making your comparisons to an int, you should instead be doing a comparison to a char, by wrapping your values in single quotations.
while(i<8){
if(binaryArray[i]=='0') {
++i;
}else if(binaryArray[i]=='1') {
switch(i) {
case 1:
integer+=128;
++i;
break;
case 2:
integer+=64;
++i;
break;
case 3:
integer+=32;
++i;
break;
case 4:
integer+=16;
++i;
break;
case 5:
integer+=8;
++i;
break;
case 6:
integer+=4;
++i;
break;
case 7:
integer+=2;
++i;
break;
case 8:
integer+=1;
++i;
break;
}
}
Others have already pointed out that you have got confused between 0 and 1, and '0' and'1'`.
Other problems:
Your i starts at 1, so you miss the most significant bit;
You will never actually hit case 8: in the switch because of the while (i < 8) loop guard.
This doesn't work unless you enter exactly 8 bits.
You can write the entire while loop in a much more concise way:
for (int i = 0; i < binaryArray.length; i++) {
integer *= 2; // shift the digits along by 1 place
if (binaryArray[i] == '1') {
integer += 1; // set the least significant bit.
}
}
You should get away from all those switch statements.
Say you have "10101101" as input.
set val = 0;
Then either multiply by val by 2 or shift left 1 bit. They're the same. It is important
you do this before adding the next bit.
Start from the left and if it's a '1', add a 1 to val. Otherwise, add 0.
Then repeat starting at multiply until you've gone thru the string.
val should then have the decimal version when you print it.

Condensing basic code using || operator with a string

I'm quite new to java programming. I was unable to find any information relating to the use of the || operator with strings. I was wondering if there was a more efficient way to do this code in particular that was still easily readable. I tried making a simple calculator as a way to familiarize myself with IfThenElse statements.
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
double first;
double second;
String option;
while(true){
System.out.println("What function would you like to calculate?");
option=input.next();
if(option.equals("add") || option.equals("+")){
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double add=first+second;
System.out.println(add);
}
else if(option.equals("subtract") || option.equals("-")) {
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double subtract=first-second;
System.out.println(subtract);
}
else if(option.equals("multiply") ||option.equals("*")) {
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double multiply=first*second;
System.out.println(multiply);
}
else if(option.equals("divide") || option.equals("/")) {
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double divide=first/second;
System.out.println(divide);
}
else if(option.equals("end")){
System.exit(0);
}
}
}
}
For the most part I am wondering about the if requirements, which I have tested and they do work, but it seems a bit clunky to me. However, any critique would be greatly appreciated.
Switch/case statements are a nice alternative to a series of ifs, and as of Java 7 you can use switch statements with strings. Note the syntactical difference between the two. Instead of grouping things with curly braces, each case ends with a break statement.
switch (option) {
case "add":
case "+":
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double add=first+second;
System.out.println(add);
break;
case "subtract":
case "-":
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double subtract=first-second;
System.out.println(subtract);
break;
case "multiply":
case "*":
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double multiply=first*second;
System.out.println(multiply);
break;
case "divide":
case "/":
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double divide=first/second;
System.out.println(divide);
break;
case "end":
System.exit(0);
}
I would then suggest combining the duplicated prompt code. If you find yourself copying and pasting code it's usually a good idea to take a step back and figure out how you can avoid the repetition. Duplicated code is a sign that you should do some refactoring.
if (option.equals("end")) {
System.exit(0);
}
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
switch (option) {
case "add":
case "+":
double add=first+second;
System.out.println(add);
break;
case "subtract":
case "-":
double subtract=first-second;
System.out.println(subtract);
break;
case "multiply":
case "*":
double multiply=first*second;
System.out.println(multiply);
break;
case "divide":
case "/":
double divide=first/second;
System.out.println(divide);
break;
}
Furthermore, you could also eliminate the duplicate printouts by using a single result variable for all of the calculations.
if (option.equals("end")) {
System.exit(0);
}
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double result;
switch (option) {
case "add": case "+": result = first + second; break;
case "subtract": case "-": result = first - second; break;
case "multiply": case "*": result = first * second; break;
case "divide": case "/": result = first / second; break;
}
System.out.println(result);
You're use of || seems fine to me. However I have a number of general suggestions to make the code better overall.
First of all, why not have isAdd, isSubtract, etc. functions? For example:
private boolean isAdd(String input){
return input.equalsIgnoreCase("add") || input.equals("+");
}
Same goes for the other operators. Than you can have code such as:
if (isAdd(option)) ...
Which is more readable than
if (input.equalsIgnoreCase("add") || input.equals("+")) ...
In a larger program, you might need to check these kinds of things more than once, and then having a method to do this becomes extra-handy. Also, this way if you want to change the definition of "add" (for example now "a" also qualifies), you change code in one place and the whole program complies.
Secondly, why not extract the bodies of these if statements into other functions? Than your code would read like so:
if (isAdd(option))
performAddition();
else if (isSubtract(option))
performSubtraction();
// .. etc
// function definitions here
Making for a much more readable program, as opposed to what you currently have.
Thirdly, notice where you put your spaces. option = input.next() looks better than option=input.next().
That's it pretty much. Good luck :)
John Kugelman and Aviv Cohn both gave good advice. I would like to add that your application will throw an InputMismatchException if you don't enter a valid number at the call to nextDouble(). Instead of your program terminating because of the exception you can prompt the user to enter a valid number after which he/she can try again.
One way to do this is by adding the following methods to SimpleCalculator:
private static Double getValidNumber()
{
Double nr = null;
while( nr == null )
{
nr = getNextDouble();
if(nr == null) System.out.println("Please enter a valid number.");
}
return nr;
}
private static Double getNextDouble()
{
Scanner input=new Scanner(System.in);
Double output = null;
try{ output = input.nextDouble(); }catch(InputMismatchException e){}
return output;
}
Then in your main method, simply replace the calls to input.nextDouble() by getValidNumber().

orphaned case error in a switch statments

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

Categories

Resources