简体   繁体   中英

How to Auto increment an ID in java

I am trying to auto increment an ID when I add a friend. Somehow I get an output as with ID (1,2,3,3,3..)

My following code for a Freunde class is

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Freunde {
    
    private static int idCache = 1;

    private final int id;
    public String Name; //Datenfeld Name
    public String Vorname; //Datenfeld Vorname
    public String Geburtsdatum; //Datenfeld Geburtsdatum
    public String Telefon; //Datenfeld Telefon
    public String Handy; //Datenfeld Handy
    public String Email; //Datenfeld E-Mail
    public String Adresse; //Datenfeld Adresse
        
    @Override
    public String toString() {
        return "Freunde{" +
                + id +
                ", '" + Name + '\'' +
                ", '" + Vorname + '\'' +
                ", '" + Telefon + '\'' +
                ", '" + Geburtsdatum + '\'' +
                 ", '" + Handy + '\'' +
                ", '" + Email + '\'' +
                ", '" + Adresse + '\'' +
                '}';
    }

    
    public ArrayList<Object> Kontakt = new ArrayList<Object>();

    
    public ArrayList<Object> Kontakt() 
    {
        return Kontakt;
    }
    
    Iterator<Object> input = Kontakt.iterator();

    /**************** Starting of set methods ************************/
    

    public void setVorname(String Vorname) {
        this.Vorname=Vorname;
        }   
    public void setName(String Name) {
        this.Name=Name;
    }
    public void setGeburtsdatum(String Geburtsdatum) {
        this.Geburtsdatum=Geburtsdatum;
    }
    public void setTelefon(String Telefon) {
        this.Telefon=Telefon;
    }
    public void setHandy(String Handy) {
        this.Handy=Handy;
    }
    public void setEmail(String Email) {
        this.Email=Email;
    }
    public void setAdresse(String Adresse) {
        this.Adresse=Adresse;
    }
    
    public Freunde() {
        this.id = idCache;
        idCache++;
    }
    
    public void setKontakt (ArrayList<Object> Kontakt) {
        this.Kontakt=Kontakt;
        }

    /****************End of set methods************************/    
    
    /****************Starting of get methods************************/
    
    public String getName() {
        return Name;
    }
    public String getTelefon() {
        return Telefon;
    }
    public String getHandy() {
        return Handy;
    }
    public String getVorname() {
        return Vorname;
    }
    public String getEmail() {
        return Email;
    }
    public String getGeburtsdatum() {
        return Geburtsdatum;
    }
    public String getAdresse() {
        return Adresse;
    }
    public ArrayList<Object> getKontakt() {
        return Kontakt;
    }  
    

    
    /****************End of get methods************************/
    

    /****************add a friend method************************/
    public void anlegen() {   
    Kontakt.add(id);
    Kontakt.add(Vorname);
    Kontakt.add(Name);
    Kontakt.add(Geburtsdatum);
    Kontakt.add(Handy);
    Kontakt.add(Telefon);
    Kontakt.add(Email);
    Kontakt.add(Adresse);
    }   
    /****************remove a friend method************************/
    public void löschen(){
//  Kontakt.remove(Id);
    Kontakt.remove(Vorname);
    Kontakt.remove(Name);
    Kontakt.remove(Geburtsdatum);
    Kontakt.remove(Handy);
    Kontakt.remove(Telefon);
    Kontakt.remove(Email);
    Kontakt.remove(Adresse);
    }
    
    /****************change a friend method************************/    
    public void ändern()
    {
//  Kontakt.set(0, "Id");
    Kontakt.set(0, Vorname);
    Kontakt.set(1, Name);
    Kontakt.set(2, Geburtsdatum);
    Kontakt.set(3, Handy);
    Kontakt.set(4, Telefon);
    Kontakt.set(5, Email);
    Kontakt.set(6, Adresse);
    }   
    /****************End of array methods************************/

    /**************** Durchsuche alles nach Name 
     * @return *********************/

    public boolean suche(String Name) {
        for (int i = 0; i < Kontakt.size(); i++) {
            if (Kontakt.get(i).equals(Name)) {
                System.out.println("element found:"+ Kontakt.get(i).equals(Name));
            } 
            
    }
        return false;
    }
    
    
    public boolean contains(String bornlist) {
        return false;
        // TODO Auto-generated method stub
        }

    public static int size() {
        // TODO Auto-generated method stub
        return 0;
    }

    public int get(int i) {
        // TODO Auto-generated method stub
        return 0;
    }

    public void contains() {
        // TODO Auto-generated method stub
    }
    
     public void setKontakt(Integer Id, String vorname, String name, String geburtsdatum, String telefon, String handy, String email, String adresse)
        {
            setVorname(vorname);
            setName(name);
            setGeburtsdatum(geburtsdatum);
            setTelefon(telefon);
            setHandy(handy);
            setEmail(email);
            setAdresse(adresse);
        }//end constructor for friend


    public void setKontakt(String vorname2, String name2) {
        // TODO Auto-generated method stub
        
    }


    public static Iterator<String> iterator() {
        // TODO Auto-generated method stub
        return null;
    }

   
    }

I get the output in an array list as

Liste der Freunde

Kontakt:Freunde{1, 'Müller', 'Thomas', '0100', '15/08/1992', '018649', 'thomas.mueller@gmx.de', 'Friee 7, 14455 Berg, Deutschland'},
Kontakt:Freunde{2, 'Müller', 'Andrea', '01700', '15/01/1998', '017849', 'andrea.mueller@gmx.de', 'Im Hafen 9, 18500 Rheinsberg, Deutschland'},

Now if I add the friends with the option 2, a list of friend is added but the ID always remains the same even though I increment the ID as idCache++ .

**[3, Anush, dmawd, dwalkndw, dwwkad, dwaklndaw, dwakdnaw, dawiiha, 3, mda, fsefjfk, awdjoaw, dawjamd, dawojda, dawmoaöd, dawödöaw]**

The class for choosing the options in adding a friend or removing a friend is noted below.

import java.util.Iterator;
import java.util.ListIterator;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;
import java.util.Random;


public class Karteiprogramm {

//  private static Integer id;
    private static Scanner input;
    private static int selection;


    /**************** Start of Menu method ************************/

    public void menu() {

        System.out.println("\nNummer der Auswahl eingeben: ");
        System.out.println("[1] Alle Freunde anzeigen");
        System.out.println("[2] Freund anlegen");
        System.out.println("[3] Freund löschen");
        System.out.println("[4] Freund bearbeiten");
        System.out.println("[5] Freund suchen");
        System.out.println("[0] Programm beenden");
    }

    /**************** End of menu method ************************/

    /**************** Start of selection method ************************/

    /****************
     * Start of Mainprogram
     * 
     * @throws IOException
     ***************************/

    public static void main(String[] args) throws IOException {

        /**************** Freunde Beispiele ************************/

        // Objekt der Klasse Freund anlegen
        // Karteikarte Freund f1;
        for (int i = 0; i <= 10; i++) {
        Freunde f1 = new Freunde();

        f1.setVorname("Thomas");
        f1.setName("Müller");
        f1.setGeburtsdatum("15/01/1992");
        f1.setTelefon("01726494800");
        f1.setHandy("01879845649");
        f1.setEmail("thomas.mueller@gmx.de");
        f1.setAdresse("Friedenstraße 7, 14455 Berg, Deutschland");

        // Karteikarte Freund f2;
        Freunde f2 = new Freunde();
        f2.setVorname("Andrea");
        f2.setName("Müller");
        f2.setGeburtsdatum("15/01/1998");
        f2.setTelefon("0177595200");
        f2.setHandy("01764591849");
        f2.setEmail("andrea.mueller@gmx.de");
        f2.setAdresse("Im Hafen 9, 18500 Rheinsberg, Deutschland");

        /**************** Ende Freunde Beispiele ************************/

        Freunde bornList = new Freunde(); // Kartei für neuen Freund

        // Freunde removeList = new Freunde ();

        Scanner input = new Scanner(System.in); // Scanner für Tastatureingabe

        Karteiprogramm Start = new Karteiprogramm(); // neues Objekt vom Typ Karteiprogramm
        Start.menü(); // Aufruf der Methode menü()

        Kartei Eingabe = new Kartei();

        int selection = input.nextInt(); // Scanner für Tastatureingabe für Integer

        /* Kartei[] data = new Kartei [1]; */
        
        while (selection != 0) {
            int nummer = 0;

            if (selection == 1) {
                for (int j = 0; j < 1; j++) {
                    System.out.println("Liste der Freunde");
                    /* Eingabe.addLists(); */
                    System.out.println("Kontakt:" + f1 + ",");
                    System.out.println("Kontakt:" + f2 + ",");
                    for (int i1 = 0; i1 < 1; i1++) {
                        System.out.println(bornList.Kontakt);
                    }
                    // System.out.println (bornList.Kontakt);
                    System.out.println("Taste drücken, um zum Menu zurückzukehren");
                    System.in.read();
                    Start.menü();
                    selection = input.nextInt();
                }

                Integer id = null;
                //              int id = f1.getId();
                if (selection == 2) { // Anlegen
                    System.out.println("Kontaktdaten");
                    System.out.println("---------------------");
                    System.out.printf("Vorname: ");
                    input = new Scanner(System.in);
                    String vorname = input.next();
                    System.out.printf("Nachname: ");
                    String name = input.next();
                    System.out.printf("Geburtstag: ");
                    String geburtsdatum = input.next();
                    System.out.printf("Festnetz: ");
                    String telefon = input.next();
                    System.out.printf("Handy: ");
                    String handy = input.next();
                    System.out.printf("Email: ");
                    String email = input.next();
                    System.out.printf("Adresse: ");
                    String adresse = input.next();

                    bornList.setKontakt(id, vorname, name, geburtsdatum, telefon, handy, email, adresse); // sets the values
                                                                                                        // for friend
                    bornList.anlegen(); // adds the friend to the array list
                    System.out.println("Taste drücken, um zum Menu zurückzukehren");
                    System.in.read();
                    Start.menü();
                    selection = input.nextInt();

                }

                if (selection == 3) { // Löschen
                    System.out.println("Welcher Freund soll gelöscht werden?");
                    System.out.println("---------------------");
                    System.out.printf("Vorname: ");
                    input = new Scanner(System.in);
                    String Vorname = input.next();
                    System.out.printf("Nachname: ");
                    String Name = input.next();
                    bornList.setKontakt(Vorname, Name); // sets up the friend to remove
                    bornList.löschen(); // removes the friend from the array list
                    System.out.println("Taste drücken, um zum Menu zurückzukehren");
                    System.in.read();
                    Start.menü();
                    selection = input.nextInt();
                }

                if (selection == 4) { // Ändern
                    System.out.println("Welcher Freund soll geändert werden?");
                    System.out.println("---------------------");
                    System.out.printf("Vorname: ");
                    input = new Scanner(System.in);
                    String vorname = input.next();
                    System.out.printf("Nachname: ");
                    String name = input.next();
                    bornList.setKontakt(vorname, name); // sets the values for friend*/

                    System.out.println("---------------------");
                    System.out.printf("Vorname: ");
                    input = new Scanner(System.in);
                    String vorname2 = input.next();
                    System.out.printf("Nachname: ");
                    String name2 = input.next();
                    System.out.printf("Geburtstag: ");
                    String geburtsdatum = input.next();
                    System.out.printf("Festnetz: ");
                    String telefon = input.next();
                    System.out.printf("Handy: ");
                    String handy = input.next();
                    System.out.printf("Email: ");
                    String email = input.next();
                    System.out.printf("Adresse: ");
                    String adresse = input.next();
                    
                    
                    bornList.setKontakt(id,vorname2, name2, geburtsdatum, telefon,handy, email, adresse);
                    bornList.ändern(); // adds the friend to the array list
                    
                    System.out.println("Taste drücken, um zum Menu zurückzukehren");
                    System.in.read();
                    Start.menü();
                    selection = input.nextInt();
                }

                if (selection == 5) { // suchen
                    System.out.println("Welcher Name wird gesucht?");
                    System.out.println("---------------------");
                    System.out.printf("Vorname: ");
                    input = new Scanner(System.in);
                    String Name = input.next();

                    if(bornList.suche(Name)) {
                        System.out.println("Name found");

                    }
                    for (int k = 0; k < 1; k++) {
                        System.out.println(bornList.Kontakt);
                    }

                    System.out.println("Taste drücken, um zum Menu zurückzukehren");
                    System.in.read();
                    Start.menü();
                    selection = input.nextInt();
                }
            }
        }
    }
    }
}

Is it something to do with public void setKontakt(...) or in /*add a friend method**/ ? Please help.

Some conventions: class is singular in general Freunde = Friends, but you have one single friend. A list is plural Kontakt = contact. And then an un-German feature: field and method names start with a small letter.

public class Freund {

private final int id;
private String name; //Datenfeld Name
...
private final List<Freund> kontakte = new ArrayList<>();


public List<Freund> kontakte() { // Do you need this?
    return kontakte;
}

 public void addKontakt(Freund kontakt) {
     kontakte.add(kontakt);
 }

 public Freund getKontaktById(int id) {
     return kontakte.stream().anyMatch(k -> k.id == id).orElse(null);
 }

 public Freund getKontaktByNamen(String vorname, String name) {
     return kontakte.stream()
             .anyMatch(k -> k.vorname.equals(vorname) && k.name.equals(name))
             .orElse(null);
 }

One should use the concrete class ArrayList only for new . Elsewhere it pays to use the more general interface List . This way methods are more powerful, and you could change the implementation in the future.

Every time you use new Freunde() you get new id. In Your main program, you have

Freunde f1 = new Freunde();
...
Freunde f2 = new Freunde();
...
Freunde bornList = new Freunde();

This is why you get [1,2,3,3,3,...] In my opinion you should have something like this: instead of Freunde bornList = new Freunde(); is hould be List<Freunde> bornList = new ArrayList<>(); and instead bornList.setKontakt(id, vorname, name, geburtsdatum, telefon, handy, email, adresse); is should be

Freunde born = new Freunde();
born.setKontakt(id, vorname, name, geburtsdatum, telefon, handy, email, adresse);
bornList.add(born);

Showing and deleting shoub be done by something like this: Freunde freunde = bornList.stream().filter(freunde -> freunde.getId()== searchId).findAny().orElse(null); and now display freunde or delete freunde by bornList.delete(freunde);

I use AtomicInteger for the auto increment ID, it's safer. Freunde objects can have their own list of freundes (kontakts).

import java.util.concurrent.atomic.AtomicInteger;
import java.util.ArrayList;


public class Freunde {
    
    private static final AtomicInteger _ID = new AtomicInteger(0);
    
    private final int id;
    private String name; 
    private String vorname; 
    private String geburtsdatum;
    private String telefon;
    private String handy;
    private String email;
    private String adresse;
    // Friends of THIS friend
    private ArrayList<Freunde> kontakts = new ArrayList<Freunde>();
    
    
    public Freunde(String name, String vorname, String geburtsdatum, String telefon, String handy, String email, String adresse){
        this.id = _ID.incrementAndGet(); 
        this.name = name; 
        this.vorname = vorname;
        this.geburtsdatum = geburtsdatum;
        this.telefon = telefon;
        this.handy = handy;
        this.email = email;
        this.adresse = adresse;
    }
    
    
    public addFriend(Freunde f){
            kontakts.add(f);
    }


    // Add your get/set methods here
    
    
    public String toString() {
        return "Freunde{" +
                + id +
                ", '" + name + '\'' +
                ", '" + vorname + '\'' +
                ", '" + telefon + '\'' +
                ", '" + geburtsdatum + '\'' +
                 ", '" + handy + '\'' +
                ", '" + email + '\'' +
                ", '" + adresse + '\'' +
                '}';
    }




     public static void main(String []args){
        ArrayList<Freunde> kontakts = new ArrayList<Freunde>();
        
        for(int i=0;i<9;i++){
           Freunde f = new Freunde("Thomas", "Müller", "15/01/1992", "01726494800", "01879845649", "thomas.mueller@gmx.de", "Friedenstraße 7, 14455 Berg, Deutschland");
           
           kontakts.add(f);
        }
       
       
       System.out.println(kontakts);
       
     }
}

Using the Freunde object, you can remove them from the kontackts ArrayList with the remove method. If you'd like to remove them based on their ID you can extend ArrayList like this:

public class Kontakts extends ArrayList<Freunde>{
    
    
    public void removeFriend(int friendId){
        
        Iterator<Freunde> iter = this.iterator();
        
        while (iter.hasNext()) {
            Freunde f = iter.next();
            if (f.getId() == friendId){
                this.remove(f);
                break;
            }
        }
        
    }
    
}

If you plan to look up friends by ID often, you might use a HashMap instead of ArrayList.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM