How to make a calculator with carried out result from previous operations
using arraylist and while loop in java?
Trying to make a calculator using arrayList. user inserts integers and
then type add, subtract, multiply, or divide which perform mathematical
operations with those integer, and when user types done , programme ends.
Here is the programme:
import java.util.Scanner;
import java.util.ArrayList;
class just{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
ArrayList<Integer> element = new ArrayList<Integer>();
String operation;
int counter;
int result = 0;
while(true){
operation = (input.nextLine()).trim();
if(operation !=null && !operation.isEmpty()){
if (operation.equalsIgnoreCase("done")){ break;}
try{
counter = Integer.parseInt(operation);
element.add(counter);
}catch(NumberFormatException e){
if("add".equalsIgnoreCase(operation)){
for( int i : element){
result += i;
}
System.out.println("Result is: "+result);
element.clear();
}else if("subtract".equalsIgnoreCase(operation…
for( int i : element){
result -= i;
}
System.out.println("Result is: "+result);
element.clear();
}else if("multiply".equalsIgnoreCase(operation…
for( int i : element){
result *= i;
}
System.out.println("Result is: "+result);
element.clear();
}else if("divide".equalsIgnoreCase(operation))…
for( int i : element){
result /= i;
}
System.out.println("Result is: "+result);
element.clear();
}else{
System.out.println("Put some numbers, then type add , multiply, subtract
or divide to get the result, or type done to exit.");
}
}
}else{
System.out.println("Please either enter an integer or type done.");
}
}
}
}
Add and subtract work fine. Multiply and divide work ok also , but if the
first operation is multiply or divide the result becomes 0, because
initial value of variable result is 0, alternatively if i make different
variable for multiply and divide with initial value 1 instead of 0, it
still doesn't work , becasue if i make different variable for multiply and
divide then i have to multiply variable result with it(because of carried
out result of previously add and/or subtract, and as the initial value of
result is 0 it will now results 0 all the time. How to overcome this
problem?
No comments:
Post a Comment