I'm new to java programming. I tried to make calculator that can do 4 basic math operations using if statement. However I don't have it working as expected. When trying to parse operator, it just finishes with else statement.
I guess I have not properly formatted if statement ?
Any help is greatly appreciated.
Thanks.
import java.util.Scanner;
import java.lang.Object;
public class calc {
public static void main(String args[]) {
System.out.println("Test kalkulator za sabiranje");
Scanner keyboard = new Scanner(System.in);
double fnum, snum, res;
String ch = "";
System.out.println("Enter first number: ");
fnum = keyboard.nextDouble();
System.out.println("Enter operation: ");
ch = keyboard.next();
if( ch == "+") {
System.out.println("Enter second number: ");
snum = keyboard.nextDouble();
res = fnum + snum;
System.out.println("Result is: "+ res);
}
else if ( ch == "-") {
System.out.println("Enter second number: ");
snum = keyboard.nextDouble();
res = fnum - snum;
System.out.println("Result is: "+ res);
}
else if ( ch == "/") {
System.out.println("Enter second number: ");
snum = keyboard.nextDouble();
res = fnum / snum;
System.out.println("Result is: "+ res);
}
else if( ch == "*") {
System.out.println("Enter second number: ");
snum = keyboard.nextDouble();
res = fnum * snum;
System.out.println("Result is: "+ res);
}
else {
System.out.println("You entered wrong operator, please try again");
}
keyboard.close();
}
}
String objects are reference objects, meaning when you type out code like
str == "+"
you're checking to see if the point in memory where str is located is equal to +. To verify if two strings equate each other, you need to use the method .equals like so
str.equals("+")
instead of == you should use equals method
Your code is fine, the problem is when you compare ch with the strings "+","-", and so on...
In java strings are Objects. Comparing objects with the == operator would only return true if the objects referrring to the same object. In order to actually compare the two objects you need to use the equals() method.
So to sum up, the correct conditions should be:
if(ch.equals("+")){ }
for every comparison.
Related
I'm trying to create a simple calculator program on Java as a simple first project as I learn Java.
Problem: After I run the program and after doing my calculation, I wanted to give the user the option on whether they want to end the program or do some more calculations. for some reason the program is not using the (if) statements that I have placed in it, it seems to skip it and end my program without allowing the user to input his choice at the end.
I'm really sorry if my question is not clear, I couldn't find a solution for my problem online, and I do apologize if my code looks really messy.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double fnum, snum, answer;
String choice, name, in;
System.out.println("Hello, whats your name?");
name = input.nextLine();
System.out.println("");
System.out.println("Oh so your name is " + name + "!");
System.out.println("");
System.out.println("This program is a calculator that will do simple calculation of two numbers");
System.out.println("There are four different options to choose from:");
boolean running = true;
CAL:
while (running) {
System.out.println("type a for Addition, b for subtraction, c for multiplication and d for division");
System.out.println("Then press enter!");
choice = input.nextLine();
while (!choice.equals("a") &&
!choice.equals("A") &&
!choice.equals("b") &&
!choice.equals("B") &&
!choice.equals("c") &&
!choice.equals("C") &&
!choice.equals("d") &&
!choice.equals("D")) {
System.out.println("Wrong choice, Please try again");
System.out.println("type a for Addition, b for subtraction, c for multiplication and d for division");
choice = input.nextLine();
}
if (choice.equals("a") || choice.equals("A")) {
System.out.println(name +" You have chosen Addition");
System.out.println("Type the first number:");
fnum = input.nextDouble();
System.out.println("Type the second number:");
snum = input.nextDouble();
System.out.println("your answer is:");
Addition addy = new Addition(fnum,snum);
System.out.println(addy.getans());
}
if (choice.equals("b") || choice.equals("B")) {
System.out.println(name +" You have chosen Subtraction");
System.out.println("Type the first number:");
fnum = input.nextDouble();
System.out.println("Type the second number:");
snum = input.nextDouble();
answer = fnum - snum;
System.out.println("your answer is:"
+ answer);
}
if (choice.equals("c") || choice.equals("C")) {
System.out.println(name +" You have chosen Multiplication");
System.out.println("Type the first number:");
fnum = input.nextDouble();
System.out.println("Type the second number:");
snum = input.nextDouble();
answer = fnum * snum;
System.out.println("your answer is:"
+ answer);
}
if (choice.equals("d") || choice.equals("D")) {
System.out.println(name +" You have chosen Addition");
System.out.println("Type the first number:");
fnum = input.nextDouble();
while (fnum == 0) {
System.out.println("invalid try again!");
fnum = input.nextDouble();
}
System.out.println("Type the second number:");
snum = input.nextDouble();
answer = fnum / snum;
System.out.println("your answer is:"
+ answer);
}
System.out.println("");
System.out.println("Thank you " + name + " for using this simple calculator :)");
System.out.println("If you would like to try again press a the press Enter, if you wish to exit press any botton and then press enter");
in = input.nextLine();
if (in.equals("a")) {
System.out.println("");
System.out.println("Thank you, please choose again");
System.out.println("");
} else {
System.out.println("Thank you and goodbye");
break;
}
}
}
}
It's a simple problem caused by nextInt/Double/etc behaviour.
Those methods don't read the following new-line character so the next nextLine will always return an empty string (the rest of the current line).
Try to change those (e.g. the addition case) with Double.parseDouble(input.nextLine());
if (choice.equals("a") || choice.equals("A")) {
System.out.println(name + " You have chosen Addition");
System.out.println("Type the first number:");
fnum = Double.parseDouble(input.nextLine());
System.out.println("Type the second number:");
snum = Double.parseDouble(input.nextLine());
System.out.println("your answer is:");
Addition addy = new Addition(fnum, snum);
System.out.println(addy.getans());
}
you can notice debugging that the last in = input.nextLine(); called to ask for user input will always be empty string.
For pure enjoyment and on my time, I'm trying to learn more about binary numbers and assembly. I have been to the local library checking out some books in order to gain more understanding of binary numbers and addition. I didn't even know before a few weeks back, one could add binary numbers with Java. I'm stumbled and have been for two days on this.
Like I said I'm trying to add binary numbers in addition and subtraction. I'm assuming I need to parse everything in order for it work properly. I feel I'm over looking something here. What exactly is missing? Any help is helpful.
As of right now, I have this:
`import java.util.Scanner;
public class binary operation {
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
boolean keepGoing = true;
String binary1, binary2;
int num1, num2;
System.out.println("Scenario: Choose (A)dd, (S)ubtract, (E)xit");
char choice = keyboard.next().charAt(0);
while(keepGoing){
if (choice == 'A' || choice == 'a'){
System.out.println("Enter 8-bit signed binary number: ");
binary1 = keyboard.next();
System.out.println("Enter another binary number: ");
binary2 = keyboard.next();
num1 = Integer.parseInt(binary1, 2);
num2 = Integer.parseInt(binary2, 2);
int sum = num1 + num2;
System.out.println(Integer.toBinaryString(sum));
}
else if(choice == 'S' || choice == 's'){
System.out.println("Enter 8-bit signed binary number: ");
binary1 = keyboard.next();
System.out.println("Enter another binary number: ");
binary2 = keyboard.next();
num1 = Integer.parseInt(binary1, 4);
num2 = Integer.parseInt(binary2, 4);
int difference = num1 - num2;
System.out.println(Integer.toBinaryString(difference));
}
else if(choice == 'E' || choice == 'e'){
System.out.println("Thank you.");
keepGoing = false;
System.exit(0);
}
if(keepGoing){
System.out.println("Choose (A)dd, (S)ubtract, (E)xit");
choice = keyboard.next().charAt(0);
}
}
The toBinaryString always prints as a 32-bit unsigned value. You need a method like.
public static String toSignedBinary(int num) {
return num < 0 ? "-" + Long.toBinaryString(-(long) num) : Integer.toBinaryString(num);
}
Kindly help me to fix this code for a Java program that simulates a simple calculator.
It reads two integers and a character. If the character is a +, the sum is printed; if it is a -, the difference is printed; if it is a *, the product is printed; if it is a /, the quotient is printed; and if it is a %, the remainder is printed.
import java.util.Scanner;
class calc {
private int a,b,and;
private char c;
public static void main (String args[])
{
System.out.println ("Enter the first Integer");
Scanner scan = new Scanner (System.in);
a=scan.nextInt();
System.out.println("Enter the second Integer");
b=scan.nextInt();
System.out.println("Enter the operation sign");
c=scan.nextChar();
if (c=='+')
and=a+b;
else if (c=='-')
and=a-b;
else if (c=='*')
and=a*b;
else if (c=='/')
and=a/b;
else if (c=='%')
and=a%b;
else
{
System.out.println("Wrong operation");
exit(0);
}
System.out.println("The result is "+ ans);
}
}
Couple of things:
Make all your variables static so that you can use them within main or i would suggest move them within main.
Use nextLine().charAt(0) instead of nextChar which isn't defined in Scanner.
Instead of newxInt(); use nextInt(); api of Scanner
out is a static field (note lower case o), so change System.Out to System.out.
do an import static java.lang.System.exit; so you could use exit(0); without any issues from compiler.
Edit: Just for OP (Make sure you give meaningful name to variables) -
import static java.lang.System.exit;
import java.util.Scanner;
public class calc {
public static void main(String args[]) {
int a, b, ans = 0;
char c;
System.out.println("Enter the first Integer");
Scanner scan = new Scanner(System.in);
a = scan.nextInt();
scan.nextLine();
System.out.println("Enter the second Integer");
b = scan.nextInt();
scan.nextLine();
System.out.println("Enter the operation sign");
c = scan.nextLine().charAt(0);
if (c == '+')
ans = a + b;
else if (c == '-')
ans = a - b;
else if (c == '*')
ans = a * b;
else if (c == '/')
ans = a / b;
else if (c == '%')
ans = a % b;
else {
System.out.println("Wrong operation");
exit(0);
}
System.out.println("The result is " + ans);
}
}
Output:
Enter the first Integer
10
Enter the second Integer
20
Enter the operation sign
+
The result is 30
Change
c=scna.nextChar();
to
c=scan.nextChar();
Also change
exit(0)
to
System.exit(0)
b=scan.newxInt(); to b=scan.nextInt();
Change all Out to out
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner taken = new Scanner(System.in);
int fnum;
int snum;
int ans;
String meth;
System.out.println("Please type method you wish to use:");
meth = taken.nextLine();
if (meth == "+" || meth == "plus") {
System.out.println("Please enter the First number:");
fnum = taken.nextInt();
System.out.println("Please enter the Second number:");
snum = taken.nextInt();
ans = fnum + snum; // This is the bit it misses even if the user goes through this method.
System.out.println("The answer is " + ans);
} else {
subCalc subCalcObject = new subCalc();
subCalcObject.subCalculator();
}
}
}
Like whats in the title my program does not + the numbers which is whats supposed to be done in the first statement and always subtracts no matter what method is chosen.
Use equals to compare the strings. == will return false so that you always go the else code.
if (meth.equals("+") || meth.equals("plus"))
equals checks for value equality while == checks for reference equality. So, when you do
meth = taken.nextLine();
meth is a different object from the constant strings "+" and "plus", so reference equality check will fail.
you have to use equals and not ==
public static void main(String[] args) {
Scanner taken = new Scanner(System.in);
int fnum;
int snum;
int ans;
String meth;
System.out.println("Please type method you wish to use:");
meth = taken.nextLine();
if (meth.equals("+") || meth.equals("plus")){
System.out.println("Please enter the First number:");
fnum = taken.nextInt();
System.out.println("Please enter the Second number:");
snum = taken.nextInt();
ans = fnum + snum; // This is the bit it misses even if the user goes through this method.
System.out.println("The answer is " + ans);
}
}
Change
if (meth == "+" || meth == "plus"){
To
if ("+".equals(meth) || "plus".equals(meth) ){
Now you can see there are adding.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am trying to build a simple calculator that operates on Double values and performs:
+
-
*
/
negation
^2
for some reason, whichever operation i specify when running the program executes the addition function. So when I try to do
5
7
*
I get 12.0 and not 35.
Any suggestions?
I would also really like some help implementing a way to quit this program when the word "exit" is entered. I was thinking something like System.exit(0);
but Im not sure how to implement. this is my code so far:
import java.util.Scanner;
public class Calc {
public static void main(String[] args)
{
double num1;
double num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println ("Enter 'exit' to quit the calculator or 'help' for more options");
System.out.println("Enter the first number:");
num1 = input.nextInt();
System.out.println ("Display:" + num1);
System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println ("Display:" + num2);
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation:");
operation = op.next();
if (operation == "+");
{
System.out.println((num1 + num2));
}
if (operation == "-"){
{
System.out.println((num1 - num2));
}
if (operation == "/"){
{
System.out.println((num1 / num2));
}
if (operation == "*"){
{
System.out.println((num1 * num2));
}
}
}
there is a semicolon at if (operation.equals("+"));
so, System.out.println((num1 + num2)); will always work
And also replace, == with .equals("+")
as == checks for reference, while equals checks for the value of the variable.
please change operation == to operation.equals("your value")
There are at least three main issues with your code...
Firstly, String comparison in Java is done using .equals not ==
Secondly...
if (operation == "+");
Has a semi-colon at the end, which basically means that even if the condition is meet, it will not run anything, but will skip to the next execution block, which is ...
{
System.out.println((num1 + num2));
}
Thirdly, you have an extra open brace ({) here...
if (operation == "-"){
{
Here...
if (operation == "/"){
{
And here...
if (operation == "*"){
{
Which is going to completely screw up your logic
You should also make use of else-if blocks as well...
Instead, try something like...
if ("+".equals(operation))//;
{
System.out.println((num1 + num2));
}
else if ("-".equals(operation)) //{
{
System.out.println((num1 - num2));
}
else if ("/".equals(operation)) //{
{
System.out.println((num1 / num2));
}
else if ("*".equals(operation)) //{
{
System.out.println((num1 * num2));
}
I've commented out the problem areas so you can see where they exists before hand
try this way
Instead of using == use .equals()
import java.util.Scanner;
public class Calc {
public static void main(String[] args)
{
double num1;
double num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println ("Enter 'exit' to quit the calculator or 'help' for more options");
System.out.println("Enter the first number:");
num1 = input.nextInt();
System.out.println ("Display:" + num1);
System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println ("Display:" + num2);
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation:");
operation = op.next();
if (operation.equals("+"))
{
System.out.println((num1 + num2));
}
if (operation.equals("-"))
{
System.out.println((num1 - num2));
}
if (operation.equals("/")){
{
System.out.println((num1 / num2));
}
if (operation.equals( "*")){
{
System.out.println((num1 * num2));
}
}
}