如何在java中实现整数值的自动递增?

如何在java中实现整数值的自动递增?,java,file-io,text-files,Java,File Io,Text Files,我有一个文本文件,其中包含如下记录: 1 Hamada PEPSI 2 Johny PEPSI int id, String name, String drink 这些记录的格式如下: 1 Hamada PEPSI 2 Johny PEPSI int id, String name, String drink 我编写了一个向这个文本文件添加记录的小方法,但每个记录的id都必须是唯一的 例如: 这些记录不可接受: 1 Hamada PEPSI 2 Johny PEPSI 1 Terry M

我有一个文本文件,其中包含如下记录:

1 Hamada PEPSI
2 Johny PEPSI
int id, String name, String drink
这些记录的格式如下:

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

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


感谢大家:

添加一个静态变量,该变量在添加产品时写入,并在写入记录后立即递增。您无法回收已删除的索引。稍微考虑一下设计,这个问题就变得无关紧要了。创建一个表示序列化数据文件的类。该类将拥有读取文件、写入文件、检索记录所需的所有方法。它还将存储文件状态的元数据,如下一个id号。每次添加记录时只需递增。+1,为初学者提供基本指导。需要注意的是,您正在调用修改静态变量的实例方法,我认为应该改用AtomicInteger。很好的建议是:AtomicInteger。可能在努布头上。我可能更喜欢将synchronized添加到这个方法中,这样就不会发生其他不好的事情。同时访问和修改文件将是一个更大的问题。此代码不起作用,id不会在每次添加新记录时增加。它会不断为每条记录添加1,因为您希望为每条新记录添加一个新id。这就行了。如果需要数据库功能,应该使用数据库。更好地说明你的要求,我可以很容易地改进。不值得我付出更多的努力。你的问题不清楚。在开始之前,您需要读取文件并找到出现的最大id,然后增加该id。关键是,你们要么对你们传递的id更聪明,要么禁止用户创建不好的id。去做吧。@duffymo请检查此解决方案并感谢您的帮助兄弟: