我有一个文本文件,其中包含以下记录:
1 Hamada PEPSI
2 Johny PEPSI
这些记录的格式如下:
int id, String name, String drink
我写了一个小方法来为这个文本文件添加记录,但每个记录的id必须是唯一的
例如: 这些记录是不可接受的:
1 Hamada PEPSI
2 Johny PEPSI
1 Terry Milk
这是我的代码:
public void addProduct(int id, String name, String drink)
{
Formatter x = null;
try{
FileWriter f = new FileWriter("C:\\Users\\فاطمة\\Downloads\\products.txt", true);
x = new Formatter(f);
x.format("%d %s %s %s%n",id,name,drink);
x.close();
}
catch(Exception e)
{
System.out.println("NO Database");
}
}
如何在输入新记录时使ID自动增加?
例如:
1 Ahmed PEPSI
2 Hamada PEPSI
3 Johny Milk
4 Terry Milk
5 Jack Miranda
6 Sarah Juice
答案 0 :(得分:2)
丑陋的代码。你是初学者,所以你需要知道可读性很重要。注意格式。
不要将消息打印到System.out。始终在catch块中至少打印堆栈跟踪。
private static int AUTO_INCREMENT_ID = 1;
public void addProduct(String name, String drink) {
Formatter x = null;
try {
FileWriter f = new FileWriter("C:\\Users\\فاطمة\\Downloads\\products.txt", true);
x = new Formatter(f);
x.format("%d %s %s %s%n",AUTO_INCREMENT_ID++,name,drink);
x.close();
} catch(Exception e) {
e.printStackTrace();
}
}
更糟糕的代码:无法更改文件;不要关闭资源。
答案 1 :(得分:0)
最后我找到了我的问题的答案,希望这对其他程序员有用。
这是代码:
public void addProduct(String name, String drink)
{
int max = 0;
Scanner y = null;
try{
y = new Scanner(new File("C:\\Users\\فاطمة\\Downloads\\products.txt"));
while(y.hasNext())
{
int a = y.nextInt(); // id
String b = y.next(); // name
String c = y.next(); // drink
max = a;
}
y.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Formatter x = null;
try{
FileWriter f = new FileWriter("C:\\Users\\فاطمة\\Downloads\\products.txt", true);
x = new Formatter(f);
x.format("%d %s %s%n",++max,name,drink);
x.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
说明:我们创建一个名为max的变量并将其初始化为零..好吧......现在如果它是第一次创建文件并向其添加记录,则第一个记录的第一个id为1 ...
如果文本文件已经存在...那么程序将搜索max id并将其递增....例如:
1 Hamada PEPSI
2 Johny MILK
然后在添加新记录时,它将具有id = 3
如果有任何错误,请告诉我们:)
感谢你们所有人:)