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;
}
}
Related
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.
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.
Use a while loop to keep asking the user to enter the order of
numbers until the user does give two numbers in the right order (first
smaller than second
Hi! i'm a beginner in java and I have this code but I can't loop the "error" message. it just prints 2 times
import java.util.Scanner;
public class Q6 {
public static void main(String[] args) {
int num1, num2;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type two numbers:");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
if (num1 < num2) {
int counter = num1;
while (counter <= num2) {
System.out.print(counter + " ");
counter = counter + 1;
}
}
else {
System.out.println("Error: the first number must be smaller than the second");
System.out.print("Please type two numbers: ");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
}
}
}
int num1,num2;
while (num1>=num2) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type two numbers");
System.out.printn("first number must be smaller than the second:)";
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
}
int num1,num2;
while (num1>=num2) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type two numbers:");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
if(num1>=num2) {
System.out.println("Error: First number must be smaller than the second.");
}
}
Somewhere around line 15 it gives me issues.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); //scanner object created
System.out.println("Enter your first number");
int nr1 = sc.nextInt();
System.out.println("Enter your second number");
int nr2 = sc.nextInt();
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.nextLine();
int ans = 0;
//somewhere around this line is where it is having the problems. it gives me the answer before i can put in my sign;
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);
System.out.println("To continue type yes");
String yes= sc.nextLine();
if(yes.equalsIgnoreCase("yes")) {
return;
}
}
}
it answers "0" whatever I enter before I can put in my sign
Enter your first number
9
Enter your second number
9
Enter your sign (+ , - , /, *)
0
To continue type yes
please tell me what I did wrong and possibly correct it so I can understand further
Try changing your sc.nextInt() lines to Integer.parseInt(sc.nextLine()). This should make your code work correctly.
EDIT: updated the code to include a while loop to make it so you can do multiple runs per your comment. This would also require you changing your last if statement to break; instead of return;
Scanner sc = new Scanner(System. in ); //scanner object created
while (true) {
System.out.println("Enter your first number");
int nr1 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your second number");
int nr2 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.nextLine();
int ans = 0;
//somewhere around this line is where it is having the problems. it gives me the answer before i can put in my sign;
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);
System.out.println("To continue type yes");
String yes = sc.nextLine();
if (!yes.equalsIgnoreCase("yes")) {
break;
}
}
Change
String anvin = sc.nextLine();
to
String anvin = sc.next();
Also keep in mind that you might divide through zero ;-)
Edit:
also change
String yes= sc.nextLine();
to
String yes= sc.next();
Instead of sc.nextLine(); use sc.next();
I would suggest you this, you can not only learn using objects but learn a better way of writing managed codes too,
Calculator.java -> a class
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
//Instantiate
Scanner input = new Scanner(System.in);
Calculations calc = new Calculations();
// Variable declarations
double answer = 0, entry1 , entry2 ;
char operator;
// Start
System.out.println("***** Welcome to the Command line calculator program *****");
System.out.print("Please enter the first number :");
entry1 = input.nextDouble();
System.out.print("Please enter the second number:");
entry2 = input.nextDouble();
System.out.println("Please enter the operation : ");
System.out.println("***** Operations :- + -> Add ; - ->Substract ; / -> Divide ; * -> Multiply ; ^ : Power *****");
operator = input.next().charAt(0);
// Switch case
switch (operator){
case '+' : answer = calc.add(entry1, entry2);
break;
case '-' : answer = calc.substract(entry1, entry2);
break;
case '/' : answer = calc.divide(entry1, entry2);
break;
case '*' : answer = calc.multiply(entry1, entry2);
break;
case '^' : answer = calc.power(entry1, entry2);
break;
}
System.out.println(entry1 + " " + operator + " " + entry2 + " = " + answer);
}
}`
Calculations.java -->another class holding calculations
import java.math.*;
public class Calculations {
// Addition Method
double add (double first, double second){
double answer = first + second;
return answer;
}
// Substraction Method
double substract (double first, double second){
double answer = first - second;
return answer;
}
// Multiplication Method
double multiply (double first, double second){
double answer = first * second;
return answer;
}
// Division Method
double divide (double first, double second){
double answer = first / second;
return answer;
}
// Power Method
double power(double a, double b){
double answer =Math.pow(a, b);
return answer;
}
}
line "int yes = Integer.parseInt(sc.nextLine());" is causing me problems in my calculator. im quite new at eclipse so any suggestions on correcting the code will be great.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your first number");
int nr1 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your second number");
int nr2 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your sign (+ , - , /, *)");
int yes = Integer.parseInt(sc.nextLine());
int ans =0;
int j = 0;
int reset =j;
java.lang.String anvin = sc.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;
}
}
}
Try replacing one of these lines where you enter a number.
String anvin = sc.nextLine();
with
int anvinNumbers = sc.nextInt(); //for example
It may not answer why your parsing of text isnt working but is hopefully a solution.
Refactored code
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); //scanner object created
int ans = 0;
//Inputs
System.out.println("Enter your first number");
int nr1 = sc.nextInt();
System.out.println("Enter your second number");
int nr2 = sc.nextInt();
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.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);
}
}
}