Hello,
I was trying to build a simple calculator using basic Java code and understand OOP better, so, I wrote this:
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num1 = input.nextInt();
System.out.println("Enter an operation: ");
String opr;
opr = input.nextLine();
if(opr == "+") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.addition();
} else if (opr == "-") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.subtraction();
} else if (opr == "*") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.multiplication();
} else if (opr == "/") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.division();
} else {
System.out.println("Please, Enter a valid operation!");
}
}
}
and another Class for math operations:
import java.util.Scanner;
public class Operation {
static int Num1;
static int Num2;
Scanner input = new Scanner(System.in);
public Operation(int x, int y) {
x = Num1;
y = Num2;
}
public void addition() {
System.out.println(Num1 + Num2);
}
public void subtraction() {
System.out.println(Num1 - Num2);
}
public void multiplication() {
System.out.println(Num1 * Num2);
}
public void division() {
System.out.println(Num1 / Num2);
}
}
but it doesn't take input for the operation, and it goes straight to the next line of code, like so:
Enter a number:
4
Enter an operation:
Please, Enter a valid operation!
Could anyone, please point my mistake?
Note: I'm a newbie in Java and programming in general. so, please don't mind me if my code isn't the best, I'm still learning.
Hello you had a couple of problems. The nextLine() will return an empty line the first time since nextInt consumes the integer only after receiving a new line char but leaves the new line char in the buffer. Additionally the equals comparison needs to be using opr.equals("+") or a switch statement. And finally your Operation class constructor had the variable assignment backwards. I have also modified the Operation private member variables to follow standard naming conventions and scoping practices. You generally want to make member variables private since if not explicitly defined they will be protected. I would recommend using a good IDE since it can catch a lot of those errors for you, try using the free IntelliJ. Here is an updated version of your code.
public class Operation {
private final int num1;
private final int num2;
public Operation(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
public void addition() {
System.out.println(num1 + num2);
}
public void subtraction() {
System.out.println(num1 - num2);
}
public void multiplication() {
System.out.println(num1 * num2);
}
public void division() {
System.out.println(num1 / num2);
}
}
And your main class
public class Calc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num1 = input.nextInt();
System.out.println("Enter an operation: ");
String opr = null;
while(opr == null || opr.length() == 0){
opr = input.nextLine();
}
switch (opr) {
case "+": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.addition();
break;
}
case "-": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.subtraction();
break;
}
case "*": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.multiplication();
break;
}
case "/": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.division();
break;
}
default:
System.out.println("Please, Enter a valid operation!");
break;
}
}
}
Use
input.next
rather than
input.nextLine
as nextInt accepts a number and the new line character \n.
In the switch ts checking for the new line character.
Related
Hi im a beginner in Java. How could i make this bais calculator simpler?
Also, i want the user to get an error if num1 or num2 arent Integers. How could i do that?
I already tried parseint and scanner.hasnextint but couldnt get them to work.
import java.util.Scanner;
public class topfirst{
public static void main(String[] args) {
int num1;
int num2;
int result;
String yesorno;
String yes = "yes";
String op;
while(yesorno.equals(yes)){
System.out.println("Please enter the first number :");
Scanner inputnum1 = new Scanner(System.in);
num1 = inputnum1.nextInt();
System.out.println("Please enter the second number :");
Scanner inputnum2 = new Scanner(System.in);
num2 = inputnum2.nextInt();
System.out.println("Please enter an operation :");
Scanner inputop = new Scanner(System.in);
op = inputop.next();
String minus = "-";
String plus = "+";
String multipl = "*";
String div = "/";
while ((!op.equals(minus)) && (!op.equals(plus)) && (!op.equals(multipl)) && (!op.equals(div)))
{
System.out.println("Incorrent operation, try again.");
op = inputop.next();
}
switch(op){
case "+":
result = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + result);
break;
case "-":
result = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + result);
break;
case "*":
result = num1 * num2;
System.out.println(num1 + " * " + num2 + " = " + result);
break;
case "/":
result = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + result);
break;
}
System.out.println("Do you want to calculate something else?");
Scanner inyesorno = new Scanner(System.in);
yesorno = inyesorno.next();
}}
}
import java.util.Scanner;
public class TopFirst {
private static final String PLUS = "+";
private static final String MINUS = "-";
private static final String MULTIPLY = "*";
private static final String DIV = "/";
private static final Scanner INPUT = new Scanner(System.in);
public static void main(String[] args) {
do {
System.out.print("Please enter the first number: ");
int num1 = readInt();
System.out.print("Please enter the second number: ");
int num2 = readInt();
System.out.print("Please enter an operator: ");
String operator = readOperator();
int result = countResult(num1, num2, operator);
System.out.printf("%d %s %d = %d%n", num1, operator, num2, result);
System.out.println("Do you want to calculate something else?");
} while (INPUT.next().equals("yes"));
}
private static String readOperator() {
String operator = INPUT.next();
if (isCorrect(operator)) {
return operator;
} else {
System.out.print("Incorrect operator, try again: ");
return readOperator();
}
}
private static int readInt() {
try {
return Integer.parseInt(INPUT.next());
} catch (NumberFormatException e) {
System.out.print("Incorrect number, try again: ");
return readInt();
}
}
private static boolean isCorrect(String operator) {
return MINUS.equals(operator)
|| PLUS.equals(operator)
|| MULTIPLY.equals(operator)
|| DIV.equals(operator);
}
private static int countResult(int num1,
int num2,
String operator) {
switch (operator) {
case PLUS:
return num1 + num2;
case MINUS:
return num1 - num2;
case MULTIPLY:
return num1 * num2;
case DIV:
return num1 / num2;
default:
return 0;
}
}
}
One Error that needs fixing before anything else:
String yesorno;
String yes = "yes";
String op;
while(yesorno.equals(yes)){
[...]
}
Your String yesorno does NOT equal "yes", so the while-loop is never executed in the first place!
I want to do a simple beginner project using methods, if statements, and user input. I am having an issue though with the calc() method. How can I return two different data types in java, and if I cannot, how could I do it, still by using more than the main method?
import java.util.Scanner; //allow user input
public class fourFunctionCalculator{
public static void main(String[] args) {
Scanner keyboardInput = new Scanner(System.in);
System.out.print("Enter your first number:"); //get first number
double num1 = keyboardInput.nextDouble();
System.out.print("Enter your operator: "); // get operator
String name = keyboardInput.next(); //grabs everything user types until a space
System.out.print("Enter your second number: "); //get second number
double num2 = keyboardInput.nextDouble();
System.out.println(calc(num1,op,num2));
}
//troublesome part is here
public static double calc(double num1, String op, double num2){
if (op == "+") {
return (num1 + num2);
}
else if (op == "-") {
return (num1 - num2);
}
else if (op == "*") {
return (num1 * num2);
}
else if (op == "/") {
return (num1 / num2);
}
else {
return ("INVALID OPERATOR");
}
}
}
you could generate a custom Exception, also you need to use the method .equals() inside the if validations, otherwise it is not going to work.
fourFunctionCalculator.java
import java.util.Scanner; //allow user input
public class fourFunctionCalculator{
public static void main(String[] args) {
Scanner keyboardInput = new Scanner(System.in);
System.out.print("Enter your first number:"); //get first number
double num1 = keyboardInput.nextDouble();
System.out.print("Enter your operator: "); // get operator
String name = keyboardInput.next(); //grabs everything user types until a space
System.out.print("Enter your second number: "); //get second number
double num2 = keyboardInput.nextDouble();
try {
System.out.println(calc(num1,name,num2));
} catch (InvalidOperatorException e) {
System.out.println(e);
}
}
public static double calc(double num1, String op, double num2){
if (op.equals("+")) {
return (num1 + num2);
}
else if (op.equals("-")) {
return (num1 - num2);
}
else if (op.equals("*")) {
return (num1 * num2);
}
else if (op.equals("/")) {enter code here
return (num1 / num2);
}
throw new InvalidOperatorException("INVALID OPERATOR : " + op);
}
}
InvalidOperatorException.java
public class InvalidOperatorException
extends RuntimeException {
private static final long serialVersionUID = 1L;
public InvalidOperatorException(String errorMessage) {
super(errorMessage);
}
}
I recommend returning an OptionalDouble object as placeholder of something valid or not...
Ex #1: return OptionalDouble.of(num1 + num2); // first if outcome
Ex #2: return OptionalDouble.empty(); // for the last else
Then your main(...) method needs to be something like...
System.out.println(calc(num1,op,num2).orElseThrow(() -> new IllegalArgumentException("INVALID OPERATOR")));
I suggest returning always String.
public static String calc(double num1, String op, double num2){
if (op == "+") {
return String.valueOf(num1 + num2);
}
else if (op == "-") {
return String.valueOf(num1 - num2);
}
else if (op == "*") {
return String.valueOf(num1 * num2);
}
else if (op == "/") {
return String.valueOf(num1 / num2);
}
else {
return ("INVALID OPERATOR");
}
}
I have designed a simple console calculator as follows but i need to create a loop where I can re run the program:
So that I won't need to run the program again and again and it can take the input from the user and run by itself.
private static Scanner op;
private static Scanner input;
private static Scanner cont;
public static void main(String args[]) {
double num1;
double num2;
double ans = 0;
double l1;
double l2;
String operation;
input = new Scanner(System.in);
System.out.println("Please input your first number:");
num1= input.nextDouble();
System.out.println("Please input the second numer:");
num2= input.nextDouble();
op = new Scanner(System.in);
System.out.println("Select your operation:");
operation = op.next();
if (operation.equals("+")){
System.out.println("Your Result is :" + (num1+num2));
}
if (operation.equals("-")){
System.out.println("Your Result is:" + (num1-num2));
}
if (operation.equals("/")){
if (num2 == 0){
System.out.println("Your Input is Invalid");}
else {
System.out.println("Your result is :" + (num1/num2));
}
}
if (operation.equals("*")){
System.out.println("Your result is:" + (num1*num2));
}
if (operation.equals("%")){
System.out.println("Your result is:" + (num1*100/num2));
}
if (operation.equals("^")){
ans= Math.pow(num1, num2);
System.out.println("Your result is:"+ans);
}
if (operation.equals("log")){
l1=Math.log(num1);
l2=Math.log(num2);
System.out.println("Your result is:"+l1/l2);
}
operation = cont.next();
System.out.println("Do you wish to perform any other operation?");
if (operation.equals("Yes")){
else{
System.out.println("Thank You");
}
}
}
you can create a function and call it with a loop like this:
private static void myfunction(){
//put your code here
}
public static void main(String[] args) {
//call your function until your condition is false
while(myconditionistrue){
myfunction();
}
}
if you want to ask your user if continue or not use this way:
private static void myfunction() {
//put your code here
}
public static void main(String[] args) {
String exit;
Scanner scan = new Scanner(System.in);
do {
//call your function or you can put all your code here
myfunction();
System.out.println("You want to continue? y : n :");
exit = scan.next();
} while (exit.equals("y"));
}
You can use a while(true) and then just exit at command:
import java.util.Scanner;
class Main {
private static Scanner op;
private static Scanner input;
private static Scanner cont;
public static void main(String args[]) {
double num1;
double num2;
double ans = 0;
double l1;
double l2;
String operation;
while (true) {
input = new Scanner(System.in);
System.out.println("Please input your first number:");
num1 = input.nextDouble();
System.out.println("Please input the second numer:");
num2 = input.nextDouble();
op = new Scanner(System.in);
System.out.println("Select your operation:");
operation = op.next();
if (operation.equals("+")) {
System.out.println("Your Result is :" + (num1 + num2));
}
if (operation.equals("-")) {
System.out.println("Your Result is:" + (num1 - num2));
}
if (operation.equals("/")) {
if (num2 == 0) {
System.out.println("Your Input is Invalid");
} else {
System.out.println("Your result is :" + (num1 / num2));
}
;
}
if (operation.equals("*")) {
System.out.println("Your result is:" + (num1 * num2));
}
if (operation.equals("%")) {
System.out.println("Your result is:" + (num1 * 100 / num2));
}
if (operation.equals("^")) {
ans = Math.pow(num1, num2);
System.out.println("Your result is:" + ans);
}
if (operation.equals("log")) {
l1 = Math.log(num1);
l2 = Math.log(num2);
System.out.println("Your result is:" + l1 / l2);
}
//cont = new Scanner(System.in);
//operation = cont.next();
System.out.println("Do you wish to perform any other operation?");
cont = new Scanner(System.in);
operation = cont.next();
if (operation.equals("Yes")) {
} else {
System.out.println("Thank You");
System.exit(0);
}
}
}
}
Test
Please input your first number:
5
Please input the second numer:
5
Select your operation:
*
Your result is:25.0
Do you wish to perform any other operation?
Yes
Please input your first number:
20
Please input the second numer:
10
Select your operation:
+
Your Result is :30.0
Do you wish to perform any other operation?
No
Thank You
As RealSkeptic stated in his comment, what you need is a loop. You can learn about loops, for example, here. The best choice for this situation is do-while loop.
I have a few more advices to your code:
You don't need to create many scanners to get more inputs than just one. One instance suffices.
When you use many if statements whose conditions are disjoint (by that I mean that if a single condition is true then the rest of the conditions is false), use else-if statements. It is more efficient. See this for more information.
Don't use empty branches in if statement. In this particular example, you can use if (!operation.equals("Yes")). The exclamation mark means negation. So if operation equals "Yes", the whole condition is evaluated as false.
Learn how to divide a complex code into functions (or methods). Generally, one function should provide one simple functionality.
Main Class
import java.util.Scanner;
class Calculator
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
Addition objecta = new Addition ();
Multiplacation objectmu = new Multiplacation();
Division objectd = new Division();
Minus objectmi = new Minus();
System.out.println("Enter operation");
System.out.println("1.Addition");
System.out.println("2.Multiplacation");
System.out.println("3.Division");
System.out.println("4.Subtraction");
input.nextLine();
int test1 = 1;
int test2 = 2;
int test3 = 3;
int test4 = 4;
if (test1 == 1)
{
Addition plus = new Addition();
plus.add();
}
if (test2 == 2)
{
Multiplacation multi = new Multiplacation();
multi.multiply();
}
if (test3 == 3)
{
Division div = new Division();
div.divide();
}
if (test4 == 4)
{
Minus mi = new Minus();
mi.subtract();
}
}
}
Classes
import java.util.Scanner;
class Addition
{
public static void add()
{
Scanner bob = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Eneter First Number");
fnum = bob.nextDouble();
System.out.println("Eneter Second Number");
snum = bob.nextDouble();
answer = fnum + snum;
System.out.println(answer);
}
}
import java.util.Scanner;
class Multiplacation
{
public static void multiply()
{
Scanner bob = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Eneter First Number");
fnum = bob.nextDouble();
System.out.println("Eneter Second Number");
snum = bob.nextDouble();
answer = fnum * snum;
System.out.println(answer);
}
}
import java.util.Scanner;
class Division
{
public static void divide()
{
Scanner bob = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Eneter First Number");
fnum = bob.nextDouble();
System.out.println("Eneter Second Number");
snum = bob.nextDouble();
answer = fnum / snum;
System.out.println(answer);
}
}
import java.util.Scanner;
class Minus
{
public static void subtract()
{
Scanner bob = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Eneter First Number");
fnum = bob.nextDouble();
System.out.println("Eneter Second Number");
snum = bob.nextDouble();
answer = fnum - snum;
System.out.println(answer);
}
}
Question
I am making a calculator and I am new to computer programming. I got the program to work but the only problem is that I cannot get the program to stop. It answers one problem then starts another one continuously. Any ideas how to stop it please comment.
I think you need to understand how to accept input from the user.
In your code, this is wrong:
input.nextLine();
int test1 = 1;
int test2 = 2;
int test3 = 3;
int test4 = 4;
Because later on, you check whether test1 is 1, test2 is 2 etc. Since you did not change the values of these variables, your conditions will always evaluate to true.
The correct way to do it is this:
int userInput = input.nextInt();
and then check the userInput variable:
if (userInput == 1) {
...
}
if (userInput == 2) {
...
}
etc
Tip: in this situation you should use else ifs:
if (userInput == 1) {
...
} else if (userInput == 2) {
...
} else if (userInput == 3) {
...
} else if (userInput == 4) {
...
}
Other improvements:
You should not create multiple scanners, one is enough.
You can declare a scanner in the Calculator class:
class Calculator {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
...
}
}
In your other classes, use Calculator.input instead of creating a new scanner. I'll give you an example:
class Addition
{
public static void add()
{
double fnum, snum, answer;
System.out.println("Eneter First Number");
fnum = Calculator.input.nextDouble();
System.out.println("Eneter Second Number");
snum = Calculator.input.nextDouble();
answer = fnum + snum;
System.out.println(answer);
}
}
This logic
if (test1 == 1)
and
if (test2 == 2)
is always going to be true.
You should be comparing
int test = input.nextInt();
if (test == test1) { // etc
You need to check the input given by the user, and since that is only one
if/if-else is the best approach to do...
if (userInput == 1) {
Addition plus = new Addition();
plus.add();
} else if (userInput == 2) {
...your code
} else if (userInput == 3) {
......your code
} else if (userInput == 4) {
......your code
}
here when math is done, you should ask again the user for another input...
and one scanner object is more than ok, you dont need to define multiple ones....
You can change your calculator class like this mentioned below so that it asks for an option when it completes execution. In similar situations you can use switch case instead of if conditions. Add an exit option to list of options to terminate program when ever user required it.
class Calculator
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
Addition objecta = new Addition ();
Multiplacation objectmu = new Multiplacation();
Division objectd = new Division();
Minus objectmi = new Minus();
while(true){
System.out.println("Enter operation");
System.out.println("1.Addition");
System.out.println("2.Multiplacation");
System.out.println("3.Division");
System.out.println("4.Subtraction");
System.out.println("5.Exit");
switch(input.nextLine()){
case "1":
Addition plus = new Addition();
plus.add();
break;
case "2":
Multiplacation multi = new Multiplacation();
multi.multiply();
break;
case "3":
Division div = new Division();
div.divide();
break;
case "4":
Minus mi = new Minus();
mi.subtract();
break;
case "5":
System.exit(0);
default:
System.out.println("Please enter valid option");
}
}
/*input.nextLine();
int test1 = 1;
int test2 = 2;
int test3 = 3;
int test4 = 4;
if (test1 == 1)
{
Addition plus = new Addition();
plus.add();
}
if (test2 == 2)
{
Multiplacation multi = new Multiplacation();
multi.multiply();
}
if (test3 == 3)
{
Division div = new Division();
div.divide();
}
if (test4 == 4)
{
Minus mi = new Minus();
mi.subtract();
}*/
}
}
I'm trying to make a calculator. These operators: x, +, -, / work fine.
But I want the user to be able to do 2 things after he gets the answer on his math problem.
Ask user if he wants to continue.
If user types in yes he gets to put in 2 numbers that it counts again.
If the user types no just shut down.
Here's my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner Minscanner = new Scanner(System.in);
int nr1 = Integer.parseInt(Minscanner.nextLine());
int nr2 = Integer.parseInt(Minscanner.nextLine());
int yes = Integer.parseInt(Minscanner.nextLine());//trying to fix reset
int ans =0;
int reset = J;/trying to make it reset if user types in yes
String anvin = Minscanner.nextLine();
if(anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
}
else if(anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
}
else if(anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
}
else if(anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
System.out.println(ans);
}
if(anvin.equalsIgnoreCase("yes")) {
return;
}
}
}
Put your code in a
do {
...
} while (condition);
loop, and in your case the condition would be something like wantToContinue if user say "yes".
Then the program will not end unless user no longer wants to calculate.
You can refactor your code as bellow. This may help you
boolean status=true;
while (status){
Scanner scanner = new Scanner(System.in);
Scanner scanner1 = new Scanner(System.in);
System.out.println("Enter your two numbers one by one :\n");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
System.out.println("Enter your operation you want to perform ? ");
int ans =0;
String option = scanner1.nextLine();
if(option.equalsIgnoreCase("+")) {
ans = num1 + num2;
}
else if(option.equalsIgnoreCase("-")) {
ans = num1 - num2;
}
else if(option.equalsIgnoreCase("*")) {
ans = num1 * num2;
}
else if(option.equalsIgnoreCase("/")) {
ans = num1 / num2;
}
System.out.println(ans);
System.out.println("you want to try again press y press j for shutdown\n");
Scanner sc = new Scanner(System.in);
String input=sc.nextLine();
if (input.equalsIgnoreCase("J")) {
System.exit(0);
} else if (input.equalsIgnoreCase("Y")) {
status = true;
}
}