简体   繁体   English

为什么选项的位置总是在变化?

[英]Why the place of the option always change?

I'm doing a phone book project in Java, using MySql for school.我正在用 Java 做一个电话簿项目,在学校使用 MySql。 I wanted to print the methods using the Class.getDeclaredMethods();我想使用Class.getDeclaredMethods();打印方法Class.getDeclaredMethods(); adding them to a Vector of type String .将它们添加到String类型的Vector中。 and invoke a menu() method that prints and accepts the option from the user using Scanner the problem is that it always changes the methods places.并调用一个menu()方法,该方法使用Scanner打印并接受用户的选项,问题在于它总是更改方法的位置。 for example it can print 0.addPerson 1.deleteContact 2.searchByChar例如它可以打印 0.addPerson 1.deleteContact 2.searchByChar

and the next time 0.deleteContact 1.addPerson 2.searchByChar.和下一次 0.deleteContact 1.addPerson 2.searchByChar。

the problem is that i have a Switch case depend on it.问题是我有一个 Switch 机箱依赖于它。 the menu function:菜单功能:

public static int menu(Vector<?> options){
        System.out.println("The Options: ");
        for (int i = 0; i < options.size(); i++) {
            System.out.println(i + ". " + options.get(i));
        }
        Scanner scanner = new Scanner(System.in);
        System.out.println("Your Choice: ");
        String optionString = scanner.nextLine();
        int option = 0;
        if(isNumber(optionString)){
            option = Integer.valueOf(optionString);
        }else{
            System.out.println("Please Choose Valid Option");
            return menu(options);
        }
        return option;
    }

the methods that get my methods:获取我的方法的方法:

public static Vector<String> getClassMethods(Class whichClass){
        Method[] methods = whichClass.getDeclaredMethods();
        Vector<String> stringMethods = new Vector<>();
        for (Method method : methods) {
            if(Modifier.toString(method.getModifiers()).equals("protected")){
                stringMethods.add(method.getName());
            }
        }
        return stringMethods;
    }

my class the connects to the data base:我的班级连接到数据库:

    private boolean getData(Person person){
    String sql = "SELECT * FROM " + DB_NAME + " WHERE name = '" + person.getName() + "' and phone_number = '" + person.getPhoneNumber() + "'";

    try {
        ResultSet resultSet = db.prepareStatement(sql).executeQuery();
        if (resultSet.next()) {
            return true;
        }
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }
    return false;
}

protected void addPerson(){
    Person person = MyUtills.createPerson();
    if(getData(person)){
        System.out.println(person.getName() + ", " + person.getPhoneNumber() + ": Already in Contacts" );
    }else{
        add(person);
    }
}

private void add(Person person) {
    String pName = person.getName();
    String pPhone = person.getPhoneNumber();
    String pAddress = person.getAddress();

    String sql = "INSERT INTO " + DB_NAME + " (name,phone_number,address)" +
                "VALUES (?,?,?)";

    try {
        statement = db.prepareStatement(sql);
        statement.setString(1,pName);
        statement.setString(2,pPhone);
        statement.setString(3,pAddress);
        statement.execute();
        System.out.println("Added Successfully");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

//delete contact by name
protected void deleteContact(){
    System.out.println("Enter Name Please");
    String name = MyUtills.readStringFromUser();
    Vector<Person> vector = checkMoreThanOne(name);
    if(vector.size() > 1){
        System.out.println("Choose One To Delete: ");
        int option = menu(vector);
        delete(vector.get(option));

    }
    System.out.println("Deleted");
}

private Vector<Person> checkMoreThanOne(String name) {
    Vector<Person> vector = new Vector<>();
    String sql = "SELECT * FROM " + DB_NAME;
    try {
        ResultSet resultSet = db.prepareStatement(sql).executeQuery();
        while(resultSet.next()){
            String pName = resultSet.getString("name");
            String pPhone = resultSet.getString("phone_number");
            String pAddress = resultSet.getString("address");
            if(pName.equals(name)){
                vector.add(new Person(pName,pPhone,pAddress));
            }
        }
        return vector;
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}


//deleting and existing contact;
private void delete(Person person){
    String sql = "DELETE FROM " + DB_NAME + " WHERE name = '" + person.getName() + "' and phone_number = '" + person.getPhoneNumber() + "'";
    try {
        statement = db.prepareStatement(sql);
        statement.execute();
        System.out.println("Deleted Successfully");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}


//creating a new table for empty data base!
private void createTable() {
    try {
        statement = db.prepareStatement(SQL_TABLE_STRING);
        statement.execute();
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

protected void searchByFirstChar(Character character){
    Vector<Person> personVector = new Vector<>();
    String sql = "SELECT * FROM newphonebook";

    try {
        ResultSet resultSet = db.prepareStatement(sql).executeQuery();
        while(resultSet.next()){
            String name = resultSet.getString("name");
            String phoneNum = resultSet.getString("phone_number");
            String address = resultSet.getString("address");
            if(character.equals(name.charAt(0))){
                personVector.add(new Person(name,phoneNum,address));
            }
        }
        System.out.println(personVector);
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }
}

public void getOptions(){
    Vector<String> options = MyUtills.getClassMethods(DBWriterReader.class);
    int option = MyUtills.menu(options);
    switch (option){
        case 0:
            addPerson();
            break;
        case 1:
             deleteContact();
            break;
        case 2:
//                searchByFirstChar();
                break;
        }
    }

}

I know it's not best written but I'm working on it to make it better The Writing and Reading from the data base works fine, its the way it prints my methods that makes the problem..我知道这不是最好的写法,但我正在努力使其更好 数据库中的写入和读取工作正常,它打印我的方法的方式导致问题..

If you need to guarantee the order of elements in a data structure, you don't use Vector -- it's not 1999 anymore.如果您需要保证数据结构中元素的顺序,则不要使用 Vector —— 现在已经不是 1999 年了。 Look at the documentation for Vector .查看Vector的文档。 You get elements in the order determined by an iterator, not as they are stored.您按照迭代器确定的顺序获取元素,而不是按照它们的存储顺序。

Change your data structure to an ArrayList , which guarantees order.将您的数据结构更改为ArrayList ,以保证顺序。 ArrayLists are also more performant in a single threaded application like yours, because unlike Vector, an ArrayList skips the overhead associated with being synchronized.在像您这样的单线程应用程序中,ArrayList 的性能也更高,因为与 Vector 不同,ArrayList 跳过了与同步相关的开销。 Using the index of the ArrayList elements may also simplify the way you construct your switch statement.使用 ArrayList 元素的索引还可以简化构造 switch 语句的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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