I had an assignment to create a calculator in two ways,
1) Method returning values.
2) Method without returning values.

I've done this with methods returning values but how could i add, subtract, divide , multiply without returning a value from methods ?

import java.io.*;
class first{
int a=5,b=2,c;
	public int add(){
	c=a+b;
	return c;
	}
	public int subtract(){
	c=a-b;
	return c;
	}
	public int divide(){
	c=a/b;
	return c;
	}
	public int multiply(){
	c=a*b;
	return c;
	}
	public void printf(){
	System.out.print("Answer is " + c);
	}
}
class main1{
public static void main (String args[])throws IOException{
String s1;
InputStreamReader ab=new InputStreamReader(System.in);
BufferedReader cd =new BufferedReader (ab);
System.out.print ("Input +, -, / or * : ");
s1=cd.readLine();
first object1= new first();
if (s1.equals("+"))
object1.add();
else if (s1.equals("-"))
object1.subtract();
else if (s1.equals("/"))
object1.divide();
else if (s1.equals("*"))
object1.multiply();
object1.printf();
}
}

In case 1, define methods which return value.
In case 2, declare some global variables and define methods that don't return values and assigns the values to those global variables.

I had an assignment to create a calculator in two ways,
1) Method returning values.
2) Method without returning values.

I've done this with methods returning values but how could i add, subtract, divide , multiply without returning a value from methods ?

import java.io.*;
class first{
int a=5,b=2,c;
	public int add(){
	c=a+b;
	return c;
	}
	public int subtract(){
	c=a-b;
	return c;
	}
	public int divide(){
	c=a/b;
	return c;
	}
	public int multiply(){
	c=a*b;
	return c;
	}
	public void printf(){
	System.out.print("Answer is " + c);
	}
}
class main1{
public static void main (String args[])throws IOException{
String s1;
InputStreamReader ab=new InputStreamReader(System.in);
BufferedReader cd =new BufferedReader (ab);
System.out.print ("Input +, -, / or * : ");
s1=cd.readLine();
first object1= new first();
if (s1.equals("+"))
object1.add();
else if (s1.equals("-"))
object1.subtract();
else if (s1.equals("/"))
object1.divide();
else if (s1.equals("*"))
object1.multiply();
object1.printf();
}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.