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().
Related
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!
You probably understand that I am a beginner, and I know that we aren't really liked by the community.
I made a multi purpose calculator a while back and now I want to expand it. In this question I will be focusing only on one class.
import java.util.Scanner;
public class Calculator {
public static void calcMenu(Scanner input){
Scanner oper = new Scanner(System.in);
System.out.println("Please input the First number:");
double anum = input.nextDouble();
System.out.println("Please input on of the following operations:");
System.out.println("+");
System.out.println("-");
System.out.println("*");
System.out.println("/");
String equ = oper.nextLine();
System.out.println("Please input the Second number:");
double bnum = input.nextDouble();
switch (equ){
case "+":
System.out.println(anum + bnum);
break;
case "-":
System.out.println(anum - bnum);
break;
case "*":
System.out.println(anum * bnum);
break;
case "/":
System.out.println(anum / bnum);
break;
}
}
}
In this Java class, the program can solve equations only with two numbers. I would like to make it like in a standard calculator, where you can input the numbers as much as you want. I would like to do it until the user types something like "done" and the application will return to the main menu.
This is probably a very nooby question but please help. And if you want to see the whole application: here's the link
This will help you out! :)
import java.util.InputMismatchException;
import java.util.Scanner;
public class Calculator {
private static double answer;
private static boolean done = false;
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
try {
new Calculator().calcExpression();
} catch (InputMismatchException e) {
System.out.println("An error occurred. ");
}
}
private void calcExpression() throws InputMismatchException {
System.out.println("Enter Your Expression Here:");
System.out.print("Num: ");
double firstNum = in.nextDouble();
in.nextLine();
while (!done) {
System.out.print("Operator: ");
String operand = in.nextLine();
if (operand.equals("=")) {
break;
}
System.out.print("Num: ");
double secondNum = in.nextDouble();
in.nextLine();
calculate(firstNum, operand, secondNum);
firstNum = answer;
}
System.out.printf("Answer is %.2f", answer);
}
private void calculate(double num1, String equ, double num2) {
switch (equ)
{
case "/":
answer = (num1 / num2);
break;
case "*":
answer = (num1 * num2);
break;
case "+":
answer = (num1 + num2);
break;
case "-":
answer = (num1 - num2);
break;
case "=":
done = true;
break;
}
}
}
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;
}
}
first time posting here and I'd like some help , I started learning java some days ago and I tried to make a very simple calculator. Here is the code :
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
while (true) {
Scanner input = new Scanner(System.in);
double input1, input2;
System.out.println("Type your calculation below");
input1 = input.nextDouble();
String operator = input.next();
input2 = input.nextDouble();
switch (operator) {
case "+":
System.out.println(input1 + input2);
break;
case "-":
System.out.println(input1 - input2);
break;
case "*":
System.out.println(input1 * input2);
break;
case "/":
System.out.println(input1 / input2);
break;
}
}
}
}
When I run this I have to type a number press space and then type the other number like this : 15 + 15. Can I somehow make it so that I don't have to press space every time? So I can type it like this : 15+15.
Also if you have any tips or if you see any mistakes I'd be happy to hear your opinion.
I would recommend using the delimiter for Scanner see below:
Scanner s = new Scanner(foo);
s.useDelimiter(" ");
// do input stuff here
I am trying to create a program that prompts the user to enter in the weight of the package and display the cost. I am new to the switch statement, which is why I feel it may have something to do with those statements. However, I return the error "cannot convert from boolean to int". I have looked at other situations where this comes up, but have not found a solution. Using == did not change it.
import java.util.Scanner;
public class Exercise03_18 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the weight of the package: ");
int weight = input.nextInt();
switch (weight) {
case weight <= 1:
System.out.println("The cost is 3.5");
break;
case weight <= 3:
System.out.println("The cost is 5.5");
break;
case weight <= 10:
System.out.println("The cost is 8.5");
break;
case weight <= 20:
System.out.println("The cost is 10.5");
default: System.out.println("The package cannot be shipped");
}
}
}
This post is relevant
Switch statement for greater-than/less-than
When you use switch you can only put equations in cases
switch(x)
{
case 1:
//...
break;
case 2:
//...
break;
}
The following is not valid Java:
case weight <= 1:
You need to rephrase the switch as a series of if statements.
if (weight <= 1) {
System.out.println("The cost is 3.5");
} else if (weight <= 3) {
System.out.println("The cost is 5.5");
} ...