Simple Calculator Java Coding Errors [duplicate] - java

This question already has answers here:
Simple Java calculator
(10 answers)
Closed 8 years ago.
Trying to make a simple calculator in Java but I keep getting errors when I try to compile it. Not sure if it's the coding or something I am doing when I compile it. Any help would be appreciated!
import java.util.Scanner;
class simple calculator { // simple calculator
public static void main(String args[]){
System.out.println("My simple calculator\n");
Scanner bucky= new Scanner(System.in);
double fnum,snum,ans;
System.out.print("Enter the first and second " +
"number : ");
a=bucky.nextFloat(); //assign the numbers
b=bucky.nextDouble(); // to respective variable
System.out.println("What operation u want to " +
"perform");
String operation;
operation=bucky.next();
switch(operation) {
case "+":
ans=a + b;
System.out.print("Sum of the two inputs = ");
System.out.print(ans);
break;
case "-":
ans=a - b;
System.out.print("Subtraction of the two inputs = ");
System.out.print(ans);
break;
case "*":
ans=a * b;
System.out.print("Multiplication of the two inputs = ");
System.out.print(ans);
break;
case "/":
ans=a / b;
System.out.print("Division of the two inputs = ");
System.out.print(ans);
break;
default : System.out.println("Give a proper operation " +
"symbol ");
break; // not required
}
}
}

Two compilation errors:
Your class name has whitespace in it: class simple calculator isn't valid, because "calculator" isn't a recognized token. Try: class SimpleCalculator. Also make it public and change the name of the file to match. (SimpleCalculator.java).
You declare variables a and b but don't give them types. Use float a = ... and double b = .... That one is a float and the other is a double is strange, but pressing on...
Other new-to-java issues to note:
You never close bucky, the scanner. This is a resource leak, and in a bigger application could be a major bug. Add bucky.close() after you read the last line from it, which is after operation = bucky.next()
the name bucky tells me absolutely nothing about what it is or what its use is. Try to use descriptive variable names. (The only main exception being single letter names for loop indices, etc).
fnum and snum are local variables that you declare but never use. Perhaps get rid of them?
Here's your code with edits made:
import java.util.Scanner;
public class SimpleCalculator { // simple calculator
public static void main(String args[]){
System.out.println("My simple calculator\n");
Scanner bucky= new Scanner(System.in);
double ans;
System.out.print("Enter the first and second " +
"number : ");
float a=bucky.nextFloat(); //assign the numbers
double b=bucky.nextDouble(); // to respective variable
System.out.println("What operation u want to " +
"perform");
String operation;
operation=bucky.next();
bucky.close();
switch(operation) {
case "+":
ans=a + b;
System.out.print("Sum of the two inputs = ");
System.out.print(ans);
break;
case "-":
ans=a - b;
System.out.print("Subtraction of the two inputs = ");
System.out.print(ans);
break;
case "*":
ans=a * b;
System.out.print("Multiplication of the two inputs = ");
System.out.print(ans);
break;
case "/":
ans=a / b;
System.out.print("Division of the two inputs = ");
System.out.print(ans);
break;
default : System.out.println("Give a proper operation " +
"symbol ");
break; // not required
}
}
}
I was able to compile it in the terminal with no trouble.

Related

JAVA CALCULATOR Exception in thread "main" java.util.InputMismatchException

Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:943)
at java.base/java.util.Scanner.next(Scanner.java:1598)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2569)
at testCalculator.main(testCalculator.java:12)
I'm trying to make a working calculator, which reads even decimal numbers, but it doesn't work. At the start it was integer valid only calculator, but within 30 minutes i tried to change it. Sadly my efforts were for nothing, anybody can help me with it? How to improve this calculator, so it can take decimal numbers without errors. Thank you very much for every answer!
import java.util.Scanner;
public class testCalculator {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
while(true){
System.out.println("First Number");
double x = read.nextDouble();
read.nextLine();
System.out.println("Second Number");
double y = read.nextDouble();
read.nextLine();
System.out.println("What you want to do? + / * - ");
String z = read.nextLine();
switch(z){
case "+":
System.out.println(x + y);
break;
case "-":
System.out.println(x - y);
break;
case "*":
System.out.println(x * y);
break;
case "/":
System.out.println (x / y);
break;
default:
System.out.println("bruh");
break;
}
}
}
Given the locale info (pl_PL) the decimal separator is a comma, e.g. 21,15.
To discover such things add the line
System.out.println(java.util.Locale.getDefault());
Use the supported locales to look it up:
https://www.oracle.com/java/technologies/javase/jdk8-jre8-suported-locales.html
And get further info on the locale:
https://www.localeplanet.com/icu/pl-PL/index.html
and reference the "Decimal separator" value: ,.

Command line calculator with multiple input numbers and operators?

Newbie to Java; I've created a Command line calculator that gets a double from user and gets one operation symbol and gets another double from user and the calculates the amount.
This is my code.
import java.util.Scanner;
public class forthProblem {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double numb1, numb2, add, subtract, multiply, divide;
char operation;
while (true) {
System.out.println("Calculate: ");
numb1 = in.nextDouble();
operation = in.next().charAt(0);
numb2 = in.nextDouble();
switch (operation) {
case '+':
add = numb1 + numb2;
System.out.println(add);
break;
case '-':
subtract = numb1 - numb2;
System.out.println(subtract);
break;
case '*':
multiply = numb1 * numb2;
System.out.println(multiply);
break;
case '/':
divide = numb1 / numb2;
System.out.println(divide);
break;
}
}
}
}
What I want to figure out is how to be able to get multiple numbers from users and do multiple operations.
for example a user could type (3+4)*4/6= and get an answer.
Also I would like to implement the bedmas in the new code.
I'll appreciate your guidance.
In order to implement PEMDAS and do multiple operations, you will need to keep all input until the user sends in '='. One way to do this is reverse polish notation. Just transform the string to RPN and then run through the equation.

Execution of do while loop in the Java Calculator program

In my Java Program, I have used a Boolean variable 'decision' which should execute the actual calculator code in the 'do loop code block' only when the variable is true, but the do while loop is executed anyways even when the decision variable is false. I am using Eclipse IDE for Java and JDK 10 (both are recent versions). Please help me with a solution. The code is as below
import java.util.Scanner;
public class apples {
public static void main(String[] args) {
int option,a,b,c;
boolean decision;
System.out.println("We are here to create a calculator");
System.out.print("Do you want to switch on the calculator:");
Scanner yogi = new Scanner(System.in);
decision = yogi.nextBoolean();
do {
System.out.println("Following operations are available to perform:");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.print("Enter the operations do you want to perform:");
option = yogi.nextInt();
System.out.println("Choice of operation is:"+option);
switch(option) {
case 1:
System.out.println("Enter two numbers to be added:");
a = yogi.nextInt();
b = yogi.nextInt();
c = a + b;
System.out.print("Addition:"+c);
break;
case 2:
System.out.println("Enter two numbers to be subtracted:");
a = yogi.nextInt();
b = yogi.nextInt();
c = a - b;
System.out.print("subtracted:"+c);
break;
case 3:
System.out.println("Enter two numbers to be multiplied:");
a = yogi.nextInt();
b = yogi.nextInt();
c = a * b;
System.out.print("multiplied:"+c);
break;
case 4:
System.out.println("Enter two numbers to be divided:");
a = yogi.nextInt();
b = yogi.nextInt();
c = a / b;
System.out.print("divided:"+c);
break;
default:
System.out.println("This is a wrong choice");
break;
}
}while(decision==true);
}
}
the do while loop is executed anyways even when the decision variable
is false
A do...while will executes the body once before checking the condition.
Either modify your code for while or add an if-else enclosing do...while.
You can add another case 5 and in that write System.exit(0) for the successful termination of the program.
In the while part pass (option != 5). This should run the program.
You don't need decision variable.

I can't seem to figure out how to display answers as words for my Calculator Project?

I have never taken a programming class before so I am very new to all of this and am having a bit of a challenge trying to get my answers to be displayed in writing. For example: if the user enters the numbers 2 and 5 and *, the answer should be displayed as two multiplied by five is 10.
Here is my program:
import java.util.Scanner;
public class CalculatorProjectCH
{//begin class
public static void main(String[] args)
{//begin main
//This program will ask the user to input two digits from 0-9 and then input a method of operation.
System.out.println("This program will act as a simple calculator. ");
System.out.println("It will ask you to enter two numbers from 0-9 and a method of operation "
+"(+, -, *, /, ^.) ");
//Declare variables input1, input2, result1, result2, result3, result4, and result5, as doubles.
double input1, input2, result1, result2, result3, result4, result5;
String text;
//Create scanner object to allow for input
Scanner input = new Scanner (System.in);
//Ask the user to enter the first number
System.out.print("\nEnter your first number: ");
input1 = input. nextDouble();
//Ask the user to enter the operation
System.out.println("Please enter the operation you would like to execute: ");
text = input.next();
//Ask the user to enter the second number
System.out.println("Enter your second number: ");
input2 = input.nextDouble();
result1= input1+input2;
result2= input1-input2;
result3= input1*input2;
result4= input1/input2;
result5= Math.pow(input1,input2);
switch (text)
{
case "+" :
System.out.println(result1);
break;
case "-" :
System.out.println(result2);
break;
case "*" :
System.out.println(result3);
break;
case "/" :
System.out.println(result4);
break;
case "^" :
System.out.println(result5);
break;
//If the user did not enter a valid method of operation
default :
System.out.println("Your operation was not recognized.");
}
}//end main
}//end class
You need to link the int value to the String version of the word somehow. I would suggest using an array:
String[] wordNumbers = new String[]{"zero","one", "two", "three"..."nine"};
Now when you need to print the String version of a number, just do this:
System.out.println(wordNumbers[0]);
Output:
zero
case "*" :
System.out.println(input1 + " multiplied by " + input2 + " is " + result3);
break;
case "/" :
System.out.println(input1 + " devided by " + input2 + " is " + result4);
break;
So I didn't change your code, just added this little part as an example to make sure what your question is about, is this what you are looking for?? And if this is it, you can just add + and - on your own with this principle.
there are another answers in stackoverflow, if you want this in your program than just tell me I can help you make it, I am just not sure what exactly you need
here I found a youtube video if you are into videos

Calculator int choice = Integer.parseInt(char_a); java

Trying to create a simple calculator on java. No errors show up in the code. But it still doesn't work at all. am I missing anything?
import java.util.Scanner;
public class JavaApplication15 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("This is a calculator. Enter a letter followed by a number to calculate it.");
System.out.println(" S = sine \n C = Cosine \n T = Tangent \n R = Square Root \n N = natural Log \n X = exit the program");
String num = in.nextLine();
String sValue = num.substring(2);
String char_a = num.substring(0);
int choice = Integer.parseInt(char_a);
double dValue = Double.parseDouble(sValue);
while (choice != 'x'){
switch(choice){
case 's':
Math.sin(dValue);
System.out.println("The sine of your number is " + dValue);
break;
case'c':
Math.cos(dValue);
System.out.println("The Cosine of your number is " + dValue);
break;
case't':
Math.tan(dValue);
System.out.println("The Tangent of your number is " + dValue);
break;
case'r':
Math.sqrt(dValue);
System.out.println("The square root of your number is " + dValue);
break;
case'n':
Math.log(dValue);
System.out.println("The Log of your number is " + dValue);
break;
case'x':
break;
}
}
}
}
I think I see your error.
You're performing operations using the Math class but aren't assigning the result of the operation back to your variable.
For example, Math.cos(dValue); should probably be dValue = Math.cos(dValue);
There are a few problems with your code.
Firstly, you are not using .substring method correctly. It returns everything from the index you specify to the end of your String. So for a user input of "S 4"
sValue equals to "4", but char_a equals to "S 4".
The way you use substring method is:
value = input.substring(2);
operation = input.substring(0,1);
I would actually suggest that you use something like:
params = input.split(" ");
Then you have:
params[0] // as your command
and
params[1] // as your value
This way you don't have to worry about how many symbols each bit actually takes up.
Next, don't convert your command to char like this. My previous suggestion means you should really be using something like
if (params[0].equals("sin")) {
} else if (params[0].equals("cos")) {
} else {
// catch unknown command
}
However, you can convert to char simply by:
sValue.toCharArray()[0]
Also, there is no reason why your switch statement should be in a while loop. There is nothing to be done continuously, it will just keep printing the same answers. And lastly, ajb said, you calculate the values and throw them away, whilst printing the old value. You have to use:
System.out.println("The Tangent of your number is " + Math.tan(dValue));

Categories