i am new to java and have been trying to learn it for a while now. This program that i am making is a basic calculator, but with the user inputting their choice of operation. I am having trouble finding out a way to put the 3 variables/operators together.
Here is what I've got.
package calulator;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String first;
String second;
String operator;
int numone;
int numtwo;
int answer;
System.out.println("Enter first number.");
first = scanner.nextLine();
numone = Integer.parseInt(first);
System.out.println("Enter operator.");
operator = scanner.nextLine();
//also don't know if i should convert this to a char or a string.
System.out.println("Enter Second number.");
second = scanner.nextLine();
numtwo = Integer.parseInt(second);
answer = numone + operator + numtwo;
//I need a way so ^^^^ that you can implement the operator.
System.out.println(answer);
}
}
switch(operator) {
case "+": answer = numone + numtwo; break;
case "-": answer = numone - numtwo; break;
case "*": answer = numone * numtwo; break;
case "/": answer = numone / numtwo; break;
// any other operators you want go here
default: throw new RuntimeException(operator+" isn't a valid operator!");
}
There is not a shorter way.
Related
I created simple calculator using switch case. When I enter the invalid operators, but it takes that value .And at last it gives the default switch case .How can I restrict it.
package calculator;
import java.util.*;
public class Calculator {
public static void main(String[] args) {
char operator;
Double num1, num2, result;
Scanner input = new Scanner(System.in);
System.out.println("Enter the operator: +,-,*,/,% ");
operator = input.next().charAt(0);
//user input
System.out.println("Enter the First Number:");
num1 = input.nextDouble();
System.out.println("Enter the Second Number:");
num2 = input.nextDouble();
switch (operator) {
case '+':
result = num1+num2;
System.out.println(num1+" + "+num1+" = " + result);
break;
case '-':
result = num1-num2;
System.out.println(num1+" - "+num1+" = " + result);
break;
case '*':
result = num1*num2;
System.out.println(num1+" * "+num1+" = " + result);
break;
case '/':
result = num1/num2;
System.out.println(num1+" / "+num1+" = " + result);
break;
case '%':
result = num1%num2;
System.out.println(num1+" % "+num1+" = " + result);
break;
default:
System.out.println("Invalid operator");
break;
}
input.close();
}
}
console output
Enter the operator: +,-,*,/,%
7
Enter the First Number:
5
Enter the Second Number:
5
Invalid operator
if(Character.isDigit(c)){
// what you want for true
}
else{
// what you want for false
}
This may help you.
Java or any other programming languages run code sequentially.
Here once the operator is entered you can check to proceed further for other statements.
The logic of code how you write, that way it is executed.
So in this case, once you take value for operator check whether that operator is allowed in your case or not.
If allowed then run the further code else not run that.
Here's A Java Calculator Program I Just Made Recently, But It Doesn't Meet My Expectations! I Want It In A More Convenient Way Like It Has 6 Classes And Some Exclamation Marks, I Wanna Get A+ So Please Help Me!
1) Can I loop the codes so after displaying the answer, It runs the code again?
2) Can I somehow decrease the number of classes and the length of codes?
3) Can I clear screen in the console like in C++, So it should display a separate view for the Intro and the answer?
Here's The Code:
import java.util.Scanner;
public class javaCalc {
public static void welcome() {
System.out.println("Welcome to Calculator.java v0.1");
System.out.println("(Developed By RAZ0229)");
}
public static void main(String[] args) {
welcome();
System.out.flush();
System.out.println("\n1) Addition");
System.out.println("2) Substraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("\nChoose A Basic Operator:");
Scanner operandOne = new Scanner(System.in);
int inpOperation = operandOne.nextInt();
switch(inpOperation) {
case 1: additionMethod();
break;
case 2: substractionMethod();
break;
case 3: multiplicationMethod();
break;
case 4: divisionMethod();
break;
default: System.out.println("\n(Invalid Argument)");
return;
}
}
public static void additionMethod() {
Scanner operandOne = new Scanner(System.in);
System.out.println("Enter The First Quantity:");
float numOne = operandOne.nextFloat();
System.out.println("Enter The Second Quantity:");
float numTwo = operandOne.nextFloat();
float answer = numOne + numTwo;
System.out.println(numOne + " + " + numTwo + " = " + answer);
}
public static void substractionMethod() {
Scanner operandOne = new Scanner(System.in);
System.out.println("Enter The First Quantity:");
float numOne = operandOne.nextFloat();
System.out.println("Enter The Second Quantity:");
float numTwo = operandOne.nextFloat();
float answer = numOne - numTwo;
System.out.println(numOne + " - " + numTwo + " = " + answer);
}
public static void multiplicationMethod() {
Scanner operandOne = new Scanner(System.in);
System.out.println("Enter The First Quantity:");
float numOne = operandOne.nextFloat();
System.out.println("Enter The Second Quantity:");
float numTwo = operandOne.nextFloat();
float answer = numOne * numTwo;
System.out.println(numOne + " x " + numTwo + " = " + answer);
}
public static void divisionMethod() {
Scanner operandOne = new Scanner(System.in);
System.out.println("Enter The First Quantity:");
float numOne = operandOne.nextFloat();
System.out.println("Enter The Second Quantity:");
float numTwo = operandOne.nextFloat();
float answer = numOne / numTwo;
System.out.println(numOne + " / " + numTwo + " = " + answer);
}
}
You are asking for two floats in every method and using the same prints many times, so you can just create some method such as this and call it inside your operation method to stop repeating code (constantly repeated blocks of code is a strong indicator that the block can probably be abstracted into its own method):
public static float[] getValues(){
float[] values;
/*Implement your logic here asking user for floats, then put into above array
and do calculations in your methods using float array*/
return values;
}
You can also loop your main by wrapping it in a while loop and adding an extra case to your switch statement like so (if you would like to exit program, enter 5):
public static void main(String[] args) {
welcome();
while (true){
System.out.flush();
System.out.println("\n1) Addition");
System.out.println("2) Substraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Quit");
System.out.println("\nChoose A Basic Operator:");
Scanner operandOne = new Scanner(System.in);
int inpOperation = operandOne.nextInt();
switch(inpOperation) {
case 1: additionMethod();
break;
case 2: substractionMethod();
break;
case 3: multiplicationMethod();
break;
case 4: divisionMethod();
break;
case 5: System.exit(0);
default: System.out.println("\n(Invalid Argument)");
return;
}
}
}
i want to input a int to get first number then use a string to get the operator and another int for the second number. user should input some thing like 10+20.
but as soon as i enter the "+" then i get an error why?
cuz it works if i manually add the values into the sum.calc(); myself like sum.calc(12, "+", 24); then it works ill get 36
PART 1:
import java.util.Scanner;
public static void main(String[] args) {
math sum = new math();
Scanner input = new Scanner(System.in);
double a = input.nextDouble();
String b = input.nextLine();
double c = input.nextDouble();
sum.calc(a, b, c);
input.close();
}
PART 2:
public class math {
public void calc(double a, String b, double c){
double t;
switch(b){
case "+":
t = a + c;
System.out.println(a+" + "+c+" = "+t);
break;
case "-":
t = a - c;
System.out.println(a+" - "+c+" = "+t);
break;
case "*":
t = a * c;
System.out.println(a+" * "+c+" = "+t);
break;
case "/":
t = a / c;
System.out.println(a+" / "+c+" = "+t);
break;
}
}
}
Try using input.next(); instead of input.nextLine(); Because input.nextLine(); advances this scanner past the current line and returns the input that was skipped. so if your input was 20, +, and 24, your method calc would get 20,24,null.
input.next() works instead of input.nextLine() for strings.Try it out
I have to make a simple calculator in java that calls methods instead of repeating the entire program over and over again. All of my methods work, and it allows the user to make incorrect choices for as long as they want until a correct choice is made. The problem I am having is that it won't break out of a case after the operation is done and the answer is given.
package menuDrivenCalculator;
import java.util.Scanner;
public class MenuDrivenCalculator {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
int menuOption = getMenuOption();
while (menuOption < 1 || menuOption > 6) {
System.out.println("I'm sorry, " + menuOption + " is not a valid choice. Please try again.");
menuOption = getMenuOption();
if (menuOption >= 1 && menuOption <= 6) {
break;
}
}
while (menuOption >= 1 && menuOption <= 6) {
switch (menuOption) {
case 1:
System.out.print("What is the first number? ");
double operand1 = getOperand();
System.out.print("What is the second number?");
double operand2 = getOperand();
double add = add(operand1, operand2);
System.out.println("Your answer is: " + add);
break;
case 2:
System.out.print("What is the first number? ");
operand1 = getOperand();
System.out.print("What is the second number?");
operand2 = getOperand();
double subtract = subtract(operand1, operand2);
System.out.println("Your answer is: " + subtract);
break;
case 3:
System.out.print("What is the first number? ");
operand1 = getOperand();
System.out.print("What is the second number?");
operand2 = getOperand();
double multiply = multiply(operand1, operand2);
System.out.println("Your answer is: " + multiply);
break;
case 4:
System.out.print("What is the first number? ");
operand1 = getOperand();
System.out.print("What is the second number?");
operand2 = getOperand();
double divide = divide(operand1, operand2);
System.out.println("Your answer is: " + divide);
break;
case 5:
System.out.print("What is the lower limit? ");
operand1 = getOperand();
System.out.print("What is the upper limit?");
operand2 = getOperand();
double random = random(operand1, operand2);
System.out.println("Your answer is: " + random);
break;
case 6:
System.out.println("Goodbye!");
return;
}
}
}
public static int getMenuOption() {
System.out.println("Menu");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Generate a random number");
System.out.println("6. Quit\n");
System.out.print("What would you like to do? ");
int menuOption = input.nextInt();
return menuOption;
}
public static double getOperand() {
double operand = input.nextDouble();
return operand;
}
public static double add(double operand1, double operand2) {
double add = (operand1 + operand2);
return add;
}
public static double subtract(double operand1, double operand2) {
double subtract = (operand1 - operand2);
return subtract;
}
public static double multiply(double operand1, double operand2) {
double multiply = (operand1 * operand2);
return multiply;
}
public static double divide(double operand1, double operand2) {
double divide = 0;
if (operand2 == 0) {
divide = Double.NaN;
} else if (operand2 != 0) {
divide = (operand1 / operand2);
}
return divide;
}
public static double random(double operand1, double operand2) {
double random = Math.random() * operand2 + operand1;
return random;
}
}
What is happening is the program prompts the user for input for the same operation over and over again until you manually stop the program from running. I've tried putting the entire thing in different types of loops and nothing has changed.
Since the code for performing the operations is inside a loop (while (menuOption >= 1 && menuOption <= 6)) the program will continue to cycle on the last chosen operation.
You need a loop that includes also the getMenuOption() method so the user can choose another operation.
To do so, instead of having 2 separate loops, you could have just 1 to take care of everything (remember also you could use the default case inside the switch).
Since it seems homework I will not give you the complete solution but if you have other specific doubts let us know.
If you dont want it to repeat over,why put the switch statement in while loop?
Replace 'while' with 'if' in your code
I need to write an application which lets the user put in two values and an operator and then calculate it. If the operator is different form +,-,/ or * the application should prompt "Wrong operator input". When it's compiled it should run something like this:
Give me number 1: 5
Give me number 2: 2
Give me an operator: +
Result: 7
The text in bold is userinput.
So far... I've got nothing. I mean I have this:
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n1;
int n2;
String o;
System.out.print("Give me number 1: ");
n1 = input.nextInt();
System.out.print("Give me number 2: ");
n2 = input.nextInt();
System.out.print("Give me an operator: ");
o = input.nextLine();
}
}
But that's about it. I have no idea how to proceed. The biggest question I have is: How do I get the users operator to be an actual operator?
Possibly something like the below would suit your needs:
Scanner input = new Scanner(System.in);
System.out.print("Give me number 1: ");
int n1 = input.nextInt();
System.out.print("Give me number 2: ");
int n2 = input.nextInt();
System.out.print("Give me an operator: ");
String o = input.next();
switch (o) {
case "+":
System.out.println(n1 + n2);
break;
case "-":
System.out.println(n1 - n2);
break;
case "*":
System.out.println(n1 * n2);
break;
case "/":
System.out.println(n1 / n2);
break;
default:
System.out.println("Error, invalid operand.");