2012-11-26 24 views
-2

如果用戶試圖輸入以前使用的ID號碼 ,我將如何去不保存記錄? 我已經嘗試了一段時間的循環,這是第二次詢問用戶的工作,它不會工作後。我想過使用數組?如何確定一個數字以前是否在變量中使用過?

import java.util.*; 

import java.io.*; 
public class CreateCustomerFile 
{ 
    public static void main(String[] args) throws IOException 
    { 
     int pos; 
     RandomAccessFile it = 
     new RandomAccessFile("CustomerFile.txt", "rw"); 
     Scanner input = new Scanner(System.in); 

     int id; 
     String name; 
     int zip; 
     final int RECORDSIZE = 100; 
     final int NUMRECORDS = 1000; 
     final int STOP = 99; 
     try 
     { 


     byte [] padding = new byte[RECORDSIZE]; 
    Arrays.fill(padding, (byte)0); 
    for(int x = 0; x < NUMRECORDS; ++x) 
    { 
     it.write(padding); 
    } 

     } 

     catch(IOException e) 
     { 
     System.out.println("Error: " + e.getMessage()); 
     } 
     finally 
     { 
     it.close(); 
     } 
     it = 
     new RandomAccessFile("CustomerFile.txt","rw"); 
     try 
     { 
     System.out.print("Enter ID number" + 
         " or " + STOP + " to quit "); 

     id = input.nextInt(); 
     while(id != STOP) 
     { 
      input.nextLine(); 

      System.out.print("Enter last name"); 
      name = input.nextLine(); 
       while(name.length() > 7 || name.length() <7) 
       { 
       System.out.print("Name must be 7 characters; Enter last name"); 
      name = input.nextLine(); 
       } 
      System.out.print("Enter zipcode "); 
      zip = input.nextInt(); 
      pos = id - 1; 
      it.seek(pos * RECORDSIZE); 
      it.writeInt(id); 
       it.writeUTF(name); 
      it.writeInt(zip); 
       System.out.print("Enter ID number" + 
       " or " + STOP + " to quit "); 
      int id1 = input.nextInt(); 

       if(id == id1) 
       { 
      System.out.print("Id has been previously used"); 

       System.out.print("Enter ID number" + 
       " or " + STOP + " to quit "); 
      id1 = input.nextInt(); 

       } 
       id = id1; 

       } 

     } 

     catch(IOException e) 
     { 
     System.out.println("Error: " + e.getMessage()); 
     } 
     finally 
     { 
     it.close(); 
     } 
    } 
    } 
+0

好了,一開始我還錯誤的印象。那麼,通過跟蹤到目前爲止與變量聯繫的方式(重複值的種類)這樣做的唯一方法。說,存儲它--->如果數組可以幫助你在最低水平,希望你知道你需要聲明的數組的長度,否則一些更好的控制像一個分區,集合。然後沖洗掉。 – bonCodigo

回答

2

您應該考慮使用UUID's的唯一標識符。

0

聽起來像你可能需要散列表/字典。

Java的哈希表/字典實現,可以發現:

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Dictionary.html

基本示例:

import java.util.*; 
public class DictionaryDemo { 
public static void main(String[] args) 
{ 
Dictionary d=new Hashtable(); 

    d.put("1", "a"); 
    d.put("2","b"); 
    d.put("3","ck"); 
    d.put("4","c"); 
    d.put("10","d"); 
    System.out.println(d.get("10")); 
    System.out.println(d.remove("10")+" has been removed"); 
    System.out.println("the value of key 10 = " +d.get("10")); 

for (Enumeration e = d.keys();e.hasMoreElements();) 
    System.out.println(e.nextElement()); 
    System.out.println(e.nextElement()); 

} 
} 
相關問題