用java制作一个简单的日记本,要求有菜单,创建日记、打开日记、编辑日记、保存、退出等,并实现其功能的代码
时间: 2023-07-10 14:26:45 浏览: 74
java代码-使用java制作一个简单的菜单界面的源代码
5星 · 资源好评率100%
好的,下面是一个简单的Java日记本代码实现:
```java
import java.util.Scanner;
import java.io.*;
public class Diary {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
boolean exit = false;
while (!exit) {
System.out.println("请选择操作:");
System.out.println("1. 创建日记");
System.out.println("2. 打开日记");
System.out.println("3. 编辑日记");
System.out.println("4. 保存日记");
System.out.println("5. 退出");
System.out.print("请选择:");
int choice = input.nextInt();
switch (choice) {
case 1:
createDiary();
break;
case 2:
openDiary();
break;
case 3:
editDiary();
break;
case 4:
saveDiary();
break;
case 5:
exit = true;
break;
default:
System.out.println("无效选项,请重新选择!");
break;
}
}
}
private static void createDiary() {
System.out.print("请输入日记文件名:");
String fileName = input.next();
try {
File file = new File(fileName);
if (file.createNewFile()) {
System.out.println("创建日记成功!");
} else {
System.out.println("日记已存在!");
}
} catch (IOException e) {
System.out.println("创建日记失败:" + e.getMessage());
}
}
private static void openDiary() {
System.out.print("请输入日记文件名:");
String fileName = input.next();
try {
FileReader reader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
reader.close();
} catch (FileNotFoundException e) {
System.out.println("打开日记失败:文件不存在!");
} catch (IOException e) {
System.out.println("打开日记失败:" + e.getMessage());
}
}
private static void editDiary() {
System.out.print("请输入日记文件名:");
String fileName = input.next();
try {
FileWriter writer = new FileWriter(fileName, true);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
System.out.println("请输入日记内容(输入end结束输入):");
String line;
while (!(line = input.nextLine()).equals("end")) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedWriter.close();
writer.close();
} catch (IOException e) {
System.out.println("编辑日记失败:" + e.getMessage());
}
}
private static void saveDiary() {
System.out.print("请输入日记文件名:");
String fileName = input.next();
try {
FileWriter writer = new FileWriter(fileName, true);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
System.out.println("请输入要保存的内容(输入end结束输入):");
String line;
while (!(line = input.nextLine()).equals("end")) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedWriter.close();
writer.close();
} catch (IOException e) {
System.out.println("保存日记失败:" + e.getMessage());
}
}
}
```
这个程序实现了菜单,包括创建日记、打开日记、编辑日记、保存、退出等功能。你可以根据自己的需要修改和完善它。
阅读全文