[英]Static method not executing completely in Try-Catch
我將對象添加到對象數組列表的靜態方法。
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循環中包含一個開關,該開關可以添加,刪除和編輯對象。
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時,它將返回到我的主方法,從而重新開始循環。 當我在開關中輸入一個字符串時,它的反應很好(重新啟動循環)。 但是我似乎無法正確添加對象。
這也是一次學校作業,他們給了我們所有這些代碼(try-catch方法除外),並要求我們為靜態方法和main方法編寫一個try-catch。 我可能會找到帶有if子句的main方法的變通方法,但是我想知道try-catch方法是否可行。
問題:
nextLine()
例如nextLine()
)和不處理該標記的方法調用( nextInt()
)。 請注意,前一個nextLine()
吞下了行尾(EOL)令牌,而nextInt()
和類似方法則不包含。 因此,如果您調用nextInt()
並使行尾令牌纏結,則調用nextLine()
不會得到您的下一行,而是會吞下懸空的EOL令牌。 一種解決方案是在調用sc.nextLine()
之后立即調用sc.nextInt()
來處理EOL令牌。 否則,在調用sc.next()
,將其更改為sc.nextLine()
。 例如,如果您有以下代碼:
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()
吞沒了用戶輸入數字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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.