簡體   English   中英

如何在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

如果有任何錯誤,請告訴我:)

感謝大家 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM