如何让java中的整数值自增?

How to make integer value auto-increment in java?

我有一个文本文件,其中包含这样的记录:

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

丑陋的代码。你是初学者,所以你需要知道可读性很重要。注意格式。

不要将消息打印到 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();
    }
}

更多错误代码:无法更改文件;不要关闭资源。

我终于找到了问题的答案,希望这对其他程序员有用。

这是代码:

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。 ..

如果文本文件已经存在...那么程序将搜索最大 ID 并递增它...例如:

  1 Hamada PEPSI
  2 Johny MILK

然后在添加新记录时它的 id = 3

如果有任何错误,请告诉我:)

感谢大家:)