用java语言写一个简易计算器并增添一些新功能并且写出文件名
时间: 2024-02-21 11:02:10 浏览: 143
好的,我可以帮你完成这个任务。以下是一个用 Java 语言编写的简易计算器的示例代码,我增加了一些新的功能,如求平方根、求余数、以及加入了一个记忆功能,可以将计算结果存储到文件中。
```
import java.util.Scanner;
import java.io.*;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double num1, num2, result;
String operator;
boolean isMemory = false;
String memoryFileName = "memory.txt";
while (true) {
System.out.print("Enter the first number: ");
num1 = input.nextDouble();
if (isMemory) {
System.out.print("Would you like to use the number in memory? (Y/N): ");
String useMemory = input.next().toUpperCase();
if (useMemory.equals("Y")) {
num1 = readMemory(memoryFileName);
} else {
isMemory = false;
}
}
System.out.print("Enter the operator (+, -, *, /, %, sqrt): ");
operator = input.next();
if (operator.equals("sqrt")) {
result = Math.sqrt(num1);
} else {
System.out.print("Enter the second number: ");
num2 = input.nextDouble();
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
case "%":
result = num1 % num2;
break;
default:
System.out.println("Invalid operator!");
continue;
}
}
System.out.println("Result: " + result);
System.out.print("Would you like to save the result to memory? (Y/N): ");
String saveMemory = input.next().toUpperCase();
if (saveMemory.equals("Y")) {
writeMemory(memoryFileName, result);
isMemory = true;
}
System.out.print("Would you like to perform another calculation? (Y/N): ");
String continueCalculation = input.next().toUpperCase();
if (continueCalculation.equals("N")) {
break;
}
}
}
public static void writeMemory(String fileName, double result) {
try {
FileWriter writer = new FileWriter(fileName);
writer.write(Double.toString(result));
writer.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
public static double readMemory(String fileName) {
try {
File file = new File(fileName);
Scanner reader = new Scanner(file);
double memory = reader.nextDouble();
reader.close();
return memory;
} catch (FileNotFoundException e) {
System.out.println("Memory file not found.");
return 0;
}
}
}
```
你可以将此代码保存为 `Calculator.java` 文件。
阅读全文