Проверка, находится ли имя клиента в текстовом файле с помощью FileReader - PullRequest
0 голосов
/ 06 марта 2012

Моя проблема в , что я должен написать код, чтобы проверить, есть ли имя клиента уже в моем текстовом файле (Customers.txt).

Как видите, я пишу имя моего клиента, каждую четвертую строку в моем текстовом файле. Я хотел бы, чтобы ввод имени клиента с SimpleInOutDialog en затем сравнивал входные данные с именем клиента в моем текстовом файле. Как мне это сделать?

Код, который у меня уже есть, находится ниже.

//make SimpleInOutDialog   
    SimpleInOutDialog  input = new SimpleInOutDialog("Customers");
    namecustomer = input.readString("Give in the name");
try{
BufferedReader br = new BufferedReader(new FileReader("L:\\Documents/Informatica/6de jaar/GIP/klanten.txt"));
HashSet<String> hs = new HashSet<String>();
int i = 0;
while ((line = br.readLine()) != null)
{
    i++;

       if (i % 4 == 0){
          if(hs.contains(namecustomer)){
             //customer exists
          input.showString("The customer exists", "");}
          else
           {setNewcustomer();}}


}
}catch (Exception e){//Catch wanneer er errors zijn
    System.err.println("Error: " + e.getMessage());}
return line;
}



public void setNewcustomer(){
    // make a newSimpleInOutDialog     
    SimpleInOutDialog  input = new SimpleInOutDialog("A new customer");
    //input
    S = "Name customer: " + input.readString("Give in your name:");
    WriteToFile();
    S = "Adress: " + input.readString("Give your adress");
    WriteToFile();
    S = "Telephonenummber: " + input.readString("Give your telephonenumber");
    WriteToFile();
    //making a customerID
      UUID idCustomer = UUID.randomUUID();  
    S = "CustomerID: " + customerID.toString();
    WriteToFile();

}

public void WriteToFile(){
try{

    FileWriter writer = new FileWriter("L:\\Documents/Informatica/6de jaar/GIP/Customer.txt", true);
    BufferedWriter out = new BufferedWriter(writer);
    //Wrting away your data
    out.write(S);

    //Closing the writer
    out.close();


}catch (Exception e){//Catch when there are errors
    System.err.println("Error: " + e.getMessage());
    }
    }

Изменения должны быть в getCustomer () Спасибо !!

Привет, Решил мою проблему, вот решение:

public void getKlant() {
    // SimpleInOutDialog aanmaken     
        SimpleInOutDialog  input = new SimpleInOutDialog("Klanten");
        naamklant = input.readString("Geef de volledige naam in");
    try{
    BufferedReader br = new BufferedReader(new FileReader("L:\\Documents/Informatica/6de jaar/GIP/klanten.txt"));
    HashSet<String> hs = new HashSet<String>();
    int i = 0;
    while ((line = br.readLine()) != null)
    {
        i++;
        if (i == 1){hs.add(br.readLine());}

        if (i % 4 == 0){hs.add(br.readLine());}

    }
    if(hs.contains(naamklant)){
        //klant bestaat
     input.showString("De klant bestaat", "");
     }else{setNieuweKlant();}


    }catch (Exception e){//Catch wanneer er errors zijn
        System.err.println("Error: " + e.getMessage());}

}

1 Ответ

2 голосов
/ 06 марта 2012

Используйте HashSet для хранения всех прочитанных вами имен, а затем просто вызовите метод содержимого, чтобы узнать, существует ли уже клиент. Если имена хранятся в четвертой строке, код должен выглядеть следующим образом

HashSet<String> hs = new HashSet<String>();
int i = 0;
while ((line = br.readLine()) != null)
{
    i++;
       if (i % 4 == 0)
       {
          if(hs.contains(line))
             //name already exist
          else
            hs.add(line);
            // new customer do what you want with it

       }
}
...