1

我将对象添加到对象数组列表的静态方法。

public static void addObject() {
    int id;
    String name;

    try{
        System.out.print("Id: ");
        id = Integer.parseInt(sc.next());

        System.out.print("Name: "); //when the program gets here, he just skips back to my main class...
        name = sc.nextLine();

        Object o = new Object(id, name);
        l.addObject(o); //adds the object to this list (l) of objects
    }
    catch(NumberFormatException nfe){
        System.out.println("Not a valid id!");
        addObject();
    }   
}

我的主要方法在 do-while-loop 中包含一个开关,用于添加、删除和编辑对象。

public static void main(String[] args){
    int choice; 
    do{ 
        try{
            choice = Integer.parseInt(sc.next());
            switch (choice){ 
                case 0: break; //ends the program
                case 1: addObject(); break; //starting static method to add an object with a name and an id

                //here are some more cases with similar static methods (left them out for simplicity)

                default: System.out.println("Not a valid choice!");break;
            }
        }
        catch(NumberFormatException nfe){
            System.out.println("Not a valid choice!");
            choice = -1; //to keep the loop running, and prevent another exception
        }

    }while (choice != 0);

System.out.println("Good bye!");

}

我的对象类

public class Object{

    private int id;
    private String name;

    public Object(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

我的 ObjectList 类

import java.util.*;

public class ObjectList {

    private List<Object> objects;

    public ObjectList() {
        objects = new ArrayList<Object>();
    }

    public void addObject(Object o){
        objects.add(d);
    }
}

当我尝试运行静态方法添加对象时,它记录了对象的 id 就好了,但是当我输入对象 id 时,它又回到我的 main 方法,开始循环。当我在开关中输入一个字符串(重新启动循环)时,它的反应很好。但我似乎无法正确添加对象。

这也是一个学校作业,他们给了我们所有这些代码(除了try-catch方法),并要求我们为静态方法和main方法编写一个try-catch。我可能可以使用 if 子句找到 main 方法的解决方法,但我想知道这是否可以使用 try-catch 方法。

4

1 回答 1

1

问题:

  • 使用 Scanner 时,您必须了解它如何处理和不处理行尾标记,尤其是当您结合处理此标记的方法调用(nextLine()例如)和不处理此标记的方法调用(nextInt()例如)时。请注意,前者会nextLine()吞下行尾 (EOL) 令牌,nextInt()而类似的方法则不会。因此,如果您调用nextInt()并留下一个行尾令牌缠结,调用nextLine()将不会得到您的下一行,而是会吞下悬空的 EOL 令牌。一种解决方案是在调用EOL 令牌sc.nextLine()后立即调用。sc.nextInt()或者你打电话的地方sc.next(),把它改成sc.nextLine().
  • 不要使用递归(让你的 addObject() 方法调用自己),因为你正在做一个简单的 while 循环会更好、更干净、更安全的地方。
  • 如果您确实有一个名为“Object”的类,请更改它,因为该名称与所有 Java 类的键基类冲突。

例如,如果您有以下代码:

Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
System.out.print("Enter name: ");
String name = sc.nextLine();

您会发现名称始终为"",这是因为sc.nextLine()正在吞噬用户输入数字时留下的行尾 (EOL) 标记。解决此问题的一种方法是:

Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
sc.nextLine();  // ***** to swallow the dangling EOL token
System.out.print("Enter name: ");
String name = sc.nextLine();
于 2013-08-20T22:07:55.207 回答