我正在尝试为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;
}
答案 0 :(得分:1)
为什么我的序列号系统会重复数字001?
因为SN
是局部变量。静态方法中的局部变量仍然是局部变量,并且每次调用方法返回时它都会消失。
您可能应该使用在封闭类中声明的static
字段....
答案 1 :(得分:0)
我想出了一种更简单的做事方式。每次我将新人添加到我的联系人列表时,我都会使用序列号来代替使用循环。
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);
}
}
}
}
}
答案 2 :(得分:0)
试试这个:
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;
int snString = i+2;
这是因为列表的索引从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;
}