Jump to content

cant do addition in java

hammad1029
Go to solution Solved by Mr_KoKa,

Change

if(input.next() == ("add"))

to

if(input.next().equals("add"))

 

next() function returns next object and object in java are all pointers, so each object has different pointer address, and comparing object directly will compare their addresses, even if contents are equal addresses are different, to compare string contents you need to use equals member function.

so i recently started learning java and right now im trying to make a calculator with the basic add, subtract, multiply and divide functions. This is the code i wrote

import java.util.Scanner;
public class test {
    public static void main(String[] args) {
        
        Scanner input = new Scanner(System.in);
        int num1; //number1
        int num2; //number2
        int num3; //the answer
        
        System.out.print("enter first number : ");
            num1 = input.nextInt();
        System.out.print("enter second number : ");
            num2 = input.nextInt();
        System.out.print("what operation do you want to use : ");
        if(input.next() == ("add"))
        {
            num3 = num1 + num2;
            System.out.print(num3);
        }
    }    
}

I havent written code for funtions other than addition because addition even isnt working(the code will more or less the same for the other functions). The error occuring is when i debug and enter the two numbers, this is what i get instead of the answer 

enter first number : 2
enter second number : 2
what operation do you want to use : add

i entered the both 2's and "add" myself. I should be getting 4 but instead nothing happens

NOTE: i started learning java 2 days 4 days ago by reading other java examples so yes im pretty new and dont know much about it either
 

Link to comment
Share on other sites

Link to post
Share on other sites

Change

if(input.next() == ("add"))

to

if(input.next().equals("add"))

 

next() function returns next object and object in java are all pointers, so each object has different pointer address, and comparing object directly will compare their addresses, even if contents are equal addresses are different, to compare string contents you need to use equals member function.

Link to comment
Share on other sites

Link to post
Share on other sites

5 minutes ago, Mr_KoKa said:

Change


if(input.next() == ("add"))

to


if(input.next().equals("add"))

 

next() function returns next object and object in java are all pointers, so each object has different pointer address, and comparing object directly will compare their addresses, even if contents are equal addresses are different, to compare string contents you need to use equals member function.

Worked like a charm, THANK YOU

Link to comment
Share on other sites

Link to post
Share on other sites

15 minutes ago, Mr_KoKa said:

Change


if(input.next() == ("add"))

to


if(input.next().equals("add"))

 

next() function returns next object and object in java are all pointers, so each object has different pointer address, and comparing object directly will compare their addresses, even if contents are equal addresses are different, to compare string contents you need to use equals member function.

ive got another error now while implementing other functions. The code is

import java.util.Scanner;
public class test {

	public static void main(String[] args) {
		
		Scanner input = new Scanner(System.in);
		int num1; //number1
		int num2; //number2
		int num3; //the answer
		
		System.out.print("enter first number : ");
			num1 = input.nextInt();
		System.out.print("enter second number : ");
			num2 = input.nextInt();
		System.out.print("what operation do you want to use : ");
		
			if(input.next().equals("add")) //addition
		{
			num3 = num1 + num2;
			System.out.print(num3);
		}
			else if(input.next().equals("subtract")); //subtraction
		{
			num3 = num1 - num2;
			System.out.print(num3);
		}
			else if(input.next().equals("multiply")); //multiplication
		{
			num3 = num1 * num2;
			System.out.print(num3);
		}
			else if(input.next().equals("divide")); //division
		{
				num3 = num1 / num2;
				System.out.print(num3);
		}
			
	}	
}

The code itself(not a problem while debugging like last time) gives me syntax errors on the 2 final else ifs after the first(there are 3 in total)

Link to comment
Share on other sites

Link to post
Share on other sites

You see, every time you do input.next() you prompt user for input, and you're doing it every if/elseif.

 

You should rather save the input to variable, like you do for numbers, and then use that variable to compare, still using equals.

 

Also there are ; at end of ifs, that is why there are syntax error reported.

Link to comment
Share on other sites

Link to post
Share on other sites

29 minutes ago, Mr_KoKa said:

You see, every time you do input.next() you prompt user for input, and you're doing it every if/elseif.

 

You should rather save the input to variable, like you do for numbers, and then use that variable to compare, still using equals.

 

Also there are ; at end of ifs, that is why there are syntax error reported.

i dont understand your first point. I removed the ';' and it doesnt give me a syntax error, however though, it doesnt show me the correct results. Additions adds 1 to the answer of everything like 4+4 gives 81 and 6+6 gives 121. Subtraction and the others dont give me any answer

Link to comment
Share on other sites

Link to post
Share on other sites

That 1 you see may be some execution result, I don't know. You can change your print to println so it will make print your result and then go to next line.

 

My point was to assign operation ot variable, cause now you ask for operation and then in first if statement you prompt user for input, if it wasn't "add" then next if you prompt user for input again.

 

if(input.next().equals("add")) /* You prompt for input there by calling input.next() */
{
  num3 = num1 + num2;
  System.out.print(num3);
}
else if(input.next().equals("subtract")); /* You prompt for input there by calling input.next() */
{
  num3 = num1 - num2;
  System.out.print(num3);
}
else if(input.next().equals("multiply")); /* You prompt for input there by calling input.next() */
{
  num3 = num1 * num2;
  System.out.print(num3);
}
else if(input.next().equals("divide")); /* You prompt for input there by calling input.next() */
{
  num3 = num1 / num2;
  System.out.print(num3);
}

instead of prompting for input every time you want to compare input against something, do it once, save result to variable and use this variable to compare against operation name.

 

String op = input.next();

if(op.equals("add"))
{

}
else if(op.equals("subtract"))
{
//... etc

 

Link to comment
Share on other sites

Link to post
Share on other sites

7 minutes ago, Mr_KoKa said:

That 1 you see may be some execution result, I don't know. You can change your print to println so it will make print your result and then go to next line.

 

My point was to assign operation ot variable, cause now you ask for operation and then in first if statement you prompt user for input, if it wasn't "add" then next if you prompt user for input again.

 


if(input.next().equals("add")) /* You prompt for input there by calling input.next() */
{
  num3 = num1 + num2;
  System.out.print(num3);
}
else if(input.next().equals("subtract")); /* You prompt for input there by calling input.next() */
{
  num3 = num1 - num2;
  System.out.print(num3);
}
else if(input.next().equals("multiply")); /* You prompt for input there by calling input.next() */
{
  num3 = num1 * num2;
  System.out.print(num3);
}
else if(input.next().equals("divide")); /* You prompt for input there by calling input.next() */
{
  num3 = num1 / num2;
  System.out.print(num3);
}

instead of prompting for input every time you want to compare input against something, do it once, save result to variable and use this variable to compare against operation name.

 


String op = input.next();

if(op.equals("add"))
{

}
else if(op.equals("subtract"))
{
//... etc

 

changing print to println just executes 1 on the next line. Your method does work. Division works perfectly for e.g

enter first number : 8
enter second number : 4
what operation do you want to use : division
2

. The others dont. In addition for e.g 6+5 makes 11 but on the next line theres the number 1

enter first number : 6
enter second number : 5
what operation do you want to use : add
11
1

Multiplication does this 

enter first number : 6
enter second number : 5
what operation do you want to use : multiply
30
1

and subtraction

enter first number : 9
enter second number : 4
what operation do you want to use : subtract
5
2

The answer appears to be always correct but there is a number in the end for some reason. The variable thing you said works but i dont understand why. My code :-

import java.util.Scanner;
public class test {

	public static void main(String[] args) {
		
		Scanner input = new Scanner(System.in);
		int num1; //number1
		int num2; //number2
		int num3; //the answer
		
		System.out.print("enter first number : ");
			num1 = input.nextInt();
		System.out.print("enter second number : ");
			num2 = input.nextInt();
		System.out.print("what operation do you want to use : ");

		String operation = input.next();

		
			if(operation.equals("add")) //addition
		{
			num3 = num1 + num2;
			System.out.println(num3);
		}
			else if(operation.equals("subtract")) //subtraction
		{
			num3 = num1 - num2;
			System.out.println(num3);
		}
			else if(operation.equals("multiply")) //multiplication
		{
			num3 = num1 * num2;
			System.out.println(num3);
		}
			else if(operation.equals("divide")); //division
		{
				num3 = num1 / num2;
				System.out.println(num3);
		}
			
	}	
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

You can try to run your jar binary elsewhere, out of IDE, that 1 appearing in the output may be something from IDE that tells you that execution of application was successful, and it may not appear when you run your application standalone.

 

To the part why variable works and your code wasn't is, input.next() prompts you for data, right? When you call this function, application stops and you have to enter somthing following with return key, after you do that application goes on.

 

When you had something like this:

if(input.next().equals("add")){ //1
} else if(input.next().equals("subtract")){ //2
} else if(input.next().equals("multiply")){ //3
} else if(input.next().equals("divide")){ //4
}

on line 1 you call next() inside if condition, if you type anything other than "add" condition won't be met, and else if will follow with another next() call, you will be asked for input there again, if it won't be "subtract" then it will proceed to next if and next next() function call, and so one, so up to 4 next() calls, where every single one will prompt user for input and pauses execution.

 

But when you do

String op = input.next(); //0

if(op.equals("add")){ //1
} else if(op.equals("subtract")){ //2
} else if(op.equals("multiply")){ //3
} else if(op.equals("divide")){ //4
}

on line 0 it will ask user for input, and it will store user input to variable, then it will compare that variable with add, subtract, multiply and divide in that order. There is only one next() call so it ask user for input only once.

Link to comment
Share on other sites

Link to post
Share on other sites

15 minutes ago, Mr_KoKa said:

You can try to run your jar binary elsewhere, out of IDE, that 1 appearing in the output may be something from IDE that tells you that execution of application was successful, and it may not appear when you run your application standalone.

 

To the part why variable works and your code wasn't is, input.next() prompts you for data, right? When you call this function, application stops and you have to enter somthing following with return key, after you do that application goes on.

 

When you had something like this:


if(input.next().equals("add")){ //1
} else if(input.next().equals("subtract")){ //2
} else if(input.next().equals("multiply")){ //3
} else if(input.next().equals("divide")){ //4
}

on line 1 you call next() inside if condition, if you type anything other than "add" condition won't be met, and else if will follow with another next() call, you will be asked for input there again, if it won't be "subtract" then it will proceed to next if and next next() function call, and so one, so up to 4 next() calls, where every single one will prompt user for input and pauses execution.

 

But when you do


String op = input.next(); //0

if(op.equals("add")){ //1
} else if(op.equals("subtract")){ //2
} else if(op.equals("multiply")){ //3
} else if(op.equals("divide")){ //4
}

on line 0 it will ask user for input, and it will store user input to variable, then it will compare that variable with add, subtract, multiply and divide in that order. There is only one next() call so it ask user for input only once.

 

I agree with grabbing the input first then your ifs though I would also suggest using a switch rather than ifs in this case

switch(op) {
case "add": num3 = num1+num2;
            break;
case "sub": num3 = num1-num2;
            break;
default: //invaild input
            break;
}

 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

19 minutes ago, Mr_KoKa said:

You can try to run your jar binary elsewhere, out of IDE, that 1 appearing in the output may be something from IDE that tells you that execution of application was successful, and it may not appear when you run your application standalone.

 

To the part why variable works and your code wasn't is, input.next() prompts you for data, right? When you call this function, application stops and you have to enter somthing following with return key, after you do that application goes on.

 

When you had something like this:


if(input.next().equals("add")){ //1
} else if(input.next().equals("subtract")){ //2
} else if(input.next().equals("multiply")){ //3
} else if(input.next().equals("divide")){ //4
}

on line 1 you call next() inside if condition, if you type anything other than "add" condition won't be met, and else if will follow with another next() call, you will be asked for input there again, if it won't be "subtract" then it will proceed to next if and next next() function call, and so one, so up to 4 next() calls, where every single one will prompt user for input and pauses execution.

 

But when you do


String op = input.next(); //0

if(op.equals("add")){ //1
} else if(op.equals("subtract")){ //2
} else if(op.equals("multiply")){ //3
} else if(op.equals("divide")){ //4
}

on line 0 it will ask user for input, and it will store user input to variable, then it will compare that variable with add, subtract, multiply and divide in that order. There is only one next() call so it ask user for input only once.

i appreciate your code but i just started learning java so the terms you used are pretty much alien for me :)

Link to comment
Share on other sites

Link to post
Share on other sites

 

31 minutes ago, Mr_KoKa said:

You can try to run your jar binary elsewhere, out of IDE, that 1 appearing in the output may be something from IDE that tells you that execution of application was successful, and it may not appear when you run your application standalone.

 

To the part why variable works and your code wasn't is, input.next() prompts you for data, right? When you call this function, application stops and you have to enter somthing following with return key, after you do that application goes on.

 

When you had something like this:


if(input.next().equals("add")){ //1
} else if(input.next().equals("subtract")){ //2
} else if(input.next().equals("multiply")){ //3
} else if(input.next().equals("divide")){ //4
}

on line 1 you call next() inside if condition, if you type anything other than "add" condition won't be met, and else if will follow with another next() call, you will be asked for input there again, if it won't be "subtract" then it will proceed to next if and next next() function call, and so one, so up to 4 next() calls, where every single one will prompt user for input and pauses execution.

 

But when you do


String op = input.next(); //0

if(op.equals("add")){ //1
} else if(op.equals("subtract")){ //2
} else if(op.equals("multiply")){ //3
} else if(op.equals("divide")){ //4
}

on line 0 it will ask user for input, and it will store user input to variable, then it will compare that variable with add, subtract, multiply and divide in that order. There is only one next() call so it ask user for input only once.

oh ok i understand about the variable part but what do you mean by different ide, and how do i do it?

Link to comment
Share on other sites

Link to post
Share on other sites

Not another IDE, but out of IDE so it won't add any output, Your IDE builds .jar file which is java executable file, you can find your project directory and find jar file, then you can open command prompt there, entering cmd in address bar and pressing enter and run java -jar yourjarname.jar

Link to comment
Share on other sites

Link to post
Share on other sites

16 hours ago, Mr_KoKa said:

Not another IDE, but out of IDE so it won't add any output, Your IDE builds .jar file which is java executable file, you can find your project directory and find jar file, then you can open command prompt there, entering cmd in address bar and pressing enter and run java -jar yourjarname.jar

I dont have a jar file, i only have .java files(in the src folder) and .class files(bin folder).

Link to comment
Share on other sites

Link to post
Share on other sites

Just gonna throw my 2 cents in there to help OP with learning to use Java. When  comparing, at least, strings, use variable.equals(), like in the solution code, because == checks if the references are equal, but equals() actually compares the content of the strings. It's down to the way strings are implemented in Java. Just a handy hint to remember down the line to save yourself from headaches

Link to comment
Share on other sites

Link to post
Share on other sites

that stray number could be Java flushing its key buffer.

CPU - Ryzen 7 3700X | RAM - 64 GB DDR4 3200MHz | GPU - Nvidia GTX 1660 ti | MOBO -  MSI B550 Gaming Plus

Link to comment
Share on other sites

Link to post
Share on other sites

On 10/10/2016 at 11:09 PM, hammad1029 said:

if(input.next() == ("add"))

replace with 

if(input.next().equalsIgnoreCase("add"))

 

CPU: Intel Core i5-6600k 4.4GHz | Motherboard: Asus ROG STRIX Z270F Gaming | Cooler: Cryorig H7 | RAM: GSkill Ripjaws V 8GB 2x4 3200 MHz | GPU: MSI GTX 1070 Gaming X | PSU: Seasonic G-550w 80+ Gold Certified, Semi Modular | Storage: 250GB Samsung 850 EVO, 1TB Western Digital Caviar Blue | Case: NZXT S340 Elite (Black/Red) | Monitor: BenQ XL2411 144hz | Keyboard: Corsair STRAFE RGB Cherry MX Silent | Mouse: Corsair M65 Pro RGB

 

I'd like to make a Chemistry joke, but all the good ones ARGON. *nudgenudge *winkwink

Link to comment
Share on other sites

Link to post
Share on other sites

14 minutes ago, FRN said:

replace with 

if(input.next().equalsIgnoreCase("add"))

 

thats already fixed by using .equals but id like it if you could help on the 1 case 

Link to comment
Share on other sites

Link to post
Share on other sites

14 hours ago, hammad1029 said:

thats already fixed by using .equals but id like it if you could help on the 1 case 

This is on console only right? What version are you using?

 

 

CPU: Intel Core i5-6600k 4.4GHz | Motherboard: Asus ROG STRIX Z270F Gaming | Cooler: Cryorig H7 | RAM: GSkill Ripjaws V 8GB 2x4 3200 MHz | GPU: MSI GTX 1070 Gaming X | PSU: Seasonic G-550w 80+ Gold Certified, Semi Modular | Storage: 250GB Samsung 850 EVO, 1TB Western Digital Caviar Blue | Case: NZXT S340 Elite (Black/Red) | Monitor: BenQ XL2411 144hz | Keyboard: Corsair STRAFE RGB Cherry MX Silent | Mouse: Corsair M65 Pro RGB

 

I'd like to make a Chemistry joke, but all the good ones ARGON. *nudgenudge *winkwink

Link to comment
Share on other sites

Link to post
Share on other sites

15 hours ago, hammad1029 said:

thats already fixed by using .equals but id like it if you could help on the 1 case 

You cant do switch on string. That's already deprecated in java 1.7. You'd have to assign a value to each operation as an instruction to your program. If I were you, I'll apply the OOP concept of Java since that is really powerful.

 

1. Create an Interface that will hold all the methods you want to use.. like this.

public interface ICalculator {
	
	public int add(int a, int b);
	public int subtract(int a, int b);
	public int multiply(int a, int b);
	public int divide(int a, int b) throws Exception;

}

2. Create another class that implements all the methods in the Interface. You could add another class for the main class but I just included the main in the second class.

import java.util.Scanner;

public class Calculator implements ICalculator {

	@Override
	public int add(int a, int b) {
		return a + b;
	}

	@Override
	public int subtract(int a, int b) {
		return a - b;
	}

	@Override
	public int multiply(int a, int b) {
		return a * b;
	}

	@Override
	public int divide(int a, int b) throws Exception {
		if (b == 0) {
			throw new Exception("Divider can't be zero");
		} return a/b;
	}
	
	public static void main(String[] args) {
		
		Calculator calc = new Calculator();
		
		Scanner s = new Scanner(System.in);
		
        System.out.println("1- Add");
        System.out.println("2- Subtract");
        System.out.println("3- Multiply");
        System.out.println("4- Divide");
        System.out.print("Select operation: ");
        int operation = s.nextInt();
        System.out.print("Enter first number: ");
		int firstNumber = s.nextInt();
		System.out.print("Enter second number: ");
		int secondNumber = s.nextInt();
		
		switch (operation) {
		case 1:
			System.out.println("Sum is: " + calc.add(firstNumber, secondNumber));
			break;
		case 2:
			System.out.println("Difference is: " + calc.subtract(firstNumber, secondNumber));
			break;
		case 3:
			System.out.println("Product is: " + calc.multiply(firstNumber, secondNumber));
			break;
		case 4:
			try {
				System.out.println("Quotient is: " + calc.divide(firstNumber, secondNumber));
				break;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

Output:

Quote

1- Add
2- Sub
3- Div
4- Mul
Select operation: 1
Enter first number: 1
Enter second number: 1
Sum is: 2

 

CPU: Intel Core i5-6600k 4.4GHz | Motherboard: Asus ROG STRIX Z270F Gaming | Cooler: Cryorig H7 | RAM: GSkill Ripjaws V 8GB 2x4 3200 MHz | GPU: MSI GTX 1070 Gaming X | PSU: Seasonic G-550w 80+ Gold Certified, Semi Modular | Storage: 250GB Samsung 850 EVO, 1TB Western Digital Caviar Blue | Case: NZXT S340 Elite (Black/Red) | Monitor: BenQ XL2411 144hz | Keyboard: Corsair STRAFE RGB Cherry MX Silent | Mouse: Corsair M65 Pro RGB

 

I'd like to make a Chemistry joke, but all the good ones ARGON. *nudgenudge *winkwink

Link to comment
Share on other sites

Link to post
Share on other sites

You can do this for the Calculator class as another option. The only downfall is that it is case sensitive.

import java.util.Scanner;

public class Calculator implements ICalculator {

	@Override
	public int add(int a, int b) {
		return a + b;
	}

	@Override
	public int subtract(int a, int b) {
		return a - b;
	}

	@Override
	public int multiply(int a, int b) {
		return a * b;
	}

	@Override
	public int divide(int a, int b) throws Exception {
		if (b == 0) {
			throw new Exception("Divider can't be zero");
		} return a/b;
	}
	
	private enum Operation {
		add,
		subtract,
		multiply,
		divide;
	}
	
	public static void main(String[] args) {
		
		Calculator calc = new Calculator();
		
		Scanner s = new Scanner(System.in);
		
		System.out.print("Select operation: ");
		
		String input = s.next();
		Operation op = Operation.valueOf(input);
		
        System.out.print("Enter first number: ");
		int firstNumber = s.nextInt();
		System.out.print("Enter second number: ");
		int secondNumber = s.nextInt();
		
		switch (op) {
		case add:
			System.out.println("Sum is: " + calc.add(firstNumber, secondNumber));
			break;
		case subtract:
			System.out.println("Difference is: " + calc.subtract(firstNumber, secondNumber));
			break;
		case multiply:
			System.out.println("Product is: " + calc.multiply(firstNumber, secondNumber));
			break;
		case divide:
			try {
				System.out.println("Quotient is: " + calc.divide(firstNumber, secondNumber));
				break;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

Output:

Quote

//Happy path

Select operation: add
Enter first number: 1
Enter second number: 1
Sum is: 2
 

//Not so happy path

Select operation: ADD
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant com.JUnitSample.Calculator.Operation.ADD
    at java.lang.Enum.valueOf(Enum.java:236)
    at com.JUnitSample.Calculator$Operation.valueOf(Calculator.java:1)
    at com.JUnitSample.Calculator.main(Calculator.java:45)

 

CPU: Intel Core i5-6600k 4.4GHz | Motherboard: Asus ROG STRIX Z270F Gaming | Cooler: Cryorig H7 | RAM: GSkill Ripjaws V 8GB 2x4 3200 MHz | GPU: MSI GTX 1070 Gaming X | PSU: Seasonic G-550w 80+ Gold Certified, Semi Modular | Storage: 250GB Samsung 850 EVO, 1TB Western Digital Caviar Blue | Case: NZXT S340 Elite (Black/Red) | Monitor: BenQ XL2411 144hz | Keyboard: Corsair STRAFE RGB Cherry MX Silent | Mouse: Corsair M65 Pro RGB

 

I'd like to make a Chemistry joke, but all the good ones ARGON. *nudgenudge *winkwink

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×