我试图在Java中为我的联系人列表分配一个唯一的ID。除了第一个数字之外,一切正常。在移动到ID002之前,它总是重复ID001两次。知道为什么吗?
private static String getSN() {
String SN = "ID001";
for (int i = 0; i < AddressBook.size(); i++) {
if(AddressBook.size()<10){
if (AddressBook.get(i).substring(0, 4).contains("ID00"+i));
int snString = i+1;
SN = "ID00"+Integer.toString(snString);
if(SN.equals("ID0010")){
SN = ("ID010");
}
}
else{
if(AddressBook.size()<100){
if (AddressBook.get(i).substring(0, 5).equals("ID0"+i));
int snString = i+1;
SN = "ID0"+Integer.toString(snString);
if(SN.equals("ID00100")){
SN = ("ID0100");
}
}
}
}
return SN;
}
为什么我的序列号系统重复数字001?
因为SN
是一个局部变量。静态方法中的局部变量仍然是局部变量,每次调用该方法返回时,它都会消失。
你可能应该使用static
字段…
我想出了一个更简单的方法。每次我向联系人列表中添加一个新成员时,我都会添加一个序列号,而不是使用循环。
private static void setSN() {
if (AddressBook.size() < 10) {
for (int i = 0; i < AddressBook.size(); i++) {
String tempString = AddressBook.get(i);
if (tempString.contains("ID00" + Integer.toString(AddressBook.size() + 1))) {
SN = "ID00" + Integer.toString(AddressBook.size() + 2);
}
else{
SN = "ID00" + Integer.toString(AddressBook.size() + 1);
}
}
}
else {
if (AddressBook.size() < 100) {
for (int i = 0; i < AddressBook.size(); i++) {
String tempString = AddressBook.get(i);
if (tempString.contains("ID0" + Integer.toString(AddressBook.size() + 1))) {
SN = "ID0" + Integer.toString(AddressBook.size() + 2);
}
else{
SN = "ID0" + Integer.toString(AddressBook.size() + 1);
}
}
}
}
}
试试这个:
1. 修改AddressBook.get(i).substring(0, 4).contains("ID00"+i)
AddressBook.get(i).substring(0, 5).contains("ID00"+(i+1))
2. 修改int snString = i+1;
byint snString = i+2;
3.这是因为列表的索引从0开始。
private static String getSN() {
String SN = "ID001";
for (int i = 0; i < AddressBook.size(); i++) {
if(AddressBook.size()<10){
if (AddressBook.get(i).substring(0, 5).contains("ID00"+(i+1))){
int snString = i+2;
SN = "ID00"+Integer.toString(snString);
}
if(SN.equals("ID0010")){
SN = ("ID010");
}
} else {
if(AddressBook.size()<100){
if (AddressBook.get(i).substring(0, 5).equals("ID0"+(i+1))) {
int snString = i+2;
SN = "ID0"+Integer.toString(snString);
}
if(SN.equals("ID00100")){
SN = ("ID0100");
}
}
}
}
return SN;
}