简体   繁体   English

静态方法未在Try-Catch中完全执行

[英]Static method not executing completely in Try-Catch

My static method to add an Object to an Arraylist of Objects. 我将对象添加到对象数组列表的静态方法。

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();
    }   
}

My main method which contains a switch in do-while-loop, which adds, deletes and edits objects. 我的主要方法是在do-while循环中包含一个开关,该开关可以添加,删除和编辑对象。

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!");

}

My Object class 我的对象类

public class Object{

    private int id;
    private String name;

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

My ObjectList class 我的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);
    }
}

When I try to run the static method to add an Object, it records the id of the object just fine, but when I enter the objects id, it goes back to my main method, starting the loop all over. 当我尝试运行静态方法以添加对象时,它会很好地记录该对象的ID,但是当我输入对象ID时,它将返回到我的主方法,从而重新开始循环。 It reacts just fine when I enter a string in the switch(restarting the loop). 当我在开关中输入一个字符串时,它的反应很好(重新启动循环)。 But I can't seem to add objects properly. 但是我似乎无法正确添加对象。

This is also a school assignment, in which they gave us all this code (except for the try-catch methods), and asked us to write a try-catch for the static method and the main method. 这也是一次学校作业,他们给了我们所有这些代码(try-catch方法除外),并要求我们为静态方法和main方法编写一个try-catch。 I could probably find a workaround for the main method with an if-clause, but I was wondering if this is possible with a try-catch method. 我可能会找到带有if子句的main方法的变通方法,但是我想知道try-catch方法是否可行。

Issues: 问题:

  • When using a Scanner, you must be aware of how it does and doesn't handle the end of line token, especially when you combine method calls that handle this token ( nextLine() for instance) and those that don't ( nextInt() for instance). 使用Scanner时,您必须知道它是如何处理行尾标记的,而不是处理行尾标记的,特别是当您组合处理该标记的方法调用nextLine()例如nextLine() )和不处理该标记的方法调用( nextInt() )。 Note that the former, nextLine() swallows the end of line (EOL) token while nextInt() and similar methods don't. 请注意,前一个nextLine()吞下了行尾(EOL)令牌,而nextInt()和类似方法则不包含。 So if you call nextInt() and leave an end of line token tangling, calling nextLine() will not get your next line, but will rather swallow the dangling EOL token. 因此,如果您调用nextInt()并使行尾令牌缠结,则调用nextLine()不会得到您的下一行,而是会吞下悬空的EOL令牌。 One solution is to call sc.nextLine() right after calling sc.nextInt() just to hande the EOL token. 一种解决方案是在调用sc.nextLine()之后立即调用sc.nextInt()来处理EOL令牌。 Or else where you call sc.next() , change that to sc.nextLine() . 否则,在调用sc.next() ,将其更改为sc.nextLine()
  • Don't use recursion (having your addObject() method call itself) as you're doing where a simple while loop will work better, will be cleaner, and safer. 在执行简单的while循环会更好,更干净,更安全的操作时,请不要使用递归(必须具有addObject()方法本身)。
  • If you truly have a class named "Object", please change it as that name conflicts with the key base class of all Java classes. 如果确实有一个名为“ Object”的类,请更改该名称,因为该名称与所有Java类的键基类冲突。

For example, if you had this code: 例如,如果您有以下代码:

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();

You'll find that the name is always "" , and that is because the sc.nextLine() is swallowing the end of line (EOL) token left over from the user's entering a number. 您会发现名称始终为"" ,这是因为sc.nextLine()吞没了用户输入数字sc.nextLine()留下的行尾(EOL)令牌。 One way to solve this is to do: 解决此问题的一种方法是:

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();

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

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