'How to append every true if, else if statement to a text file?
How do I append every user chosen equation in an if, else if statement to a text file. I am not sure where would the best place be to put the append to file because putting it in under every else if statement seems repetitive.
import java.util.Formatter;
import java.util.Scanner;
public class javaCalculator {
public static void main(String[] args){
Scanner numbers = new Scanner(System.in);
Scanner operation = new Scanner(System.in);
double number1;
double number2;
String operator;
System.out.print("Enter the operator you would like to choose(+, -, *, /): ");
operator = operation.next();
System.out.print("Enter the first number: ");
number1 = Double.parseDouble(numbers.nextLine());
System.out.print("Enter your second number: ");
number2 = Double.parseDouble(numbers.nextLine());
if (operator.equals("+")){
String calculation = (number1 + " + " + number2 + " = " + (number1 + number2));
}else if (operator.equals("-")){
String calculation = (number1 + " - " + number2 + " = " + (number1 - number2));
}else if (operator.equals("*")){
String calculation = (number1 + " * " + number2 + " = " + (number1 * number2));
}else if (operator.equals("/")){
String calculation = (number1 + " / " + number2 + " = " + (number1 / number2));
}else{
String calculation = (operator + ":" + " Is not a valid operator!");
}
try {
Formatter file1 = new Formatter("C:\\Users\\27711\\Desktop\\PROGRAMMING\\java\\JavaCalculator");
file1.format(calculation);
}
catch (Exception e){
System.out.println("Error");
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
