2017-03-17 1 views
-1

처음에는 코드가 잘 돌아가고 있지만 while 루프에서는 사용자에게 다음 입력을 요구하지 않고 이러한 요소 예외가없는 경우에만 응답합니다. 나는 그것을 적어도 1 시간 동안 고치려고 노력했지만 행운이 없었다. 무엇이 잘못되었을 지에 대한 조언이 있습니까?NoSuchElementException 첫 반복 후에 while 루프가 중단됩니까?

Welcome to the Inventory Application. You can add an item, display the stock for an item, or discontinue an item. 
Please select an option and type the option number. 
0. Quit 
1. Add an item 
2. Display stock for an item 
3. Discontinue an item 
1 
Item Name: 
test 
Item Amount: 
120 
Item added. Information: test 
Current amount in inventory is: 120 
Please select an option and type the option number. 
0. Quit 
1. Add an item 
2. Display stock for an item 
3. Discontinue an item 
java.util.NoSuchElementException 
    at java.util.Scanner.throwFor(Scanner.java:862) 
    at java.util.Scanner.next(Scanner.java:1371) 
    at Inventory.main(Inventory.java:24) 

편집 :에

 public class Inventory { 
     public static void main(String[] args) { 
     Store store = new Store(); 
     String itemName; 

     System.out.println("Welcome to the Inventory Application. You can add an item, display the stock for an item, or discontinue an item."); 
     boolean condition = true; 
     Scanner s = new Scanner(System.in); 
     do{ 
      System.out.println("Please select an option and type the option number." + "\n 0. Quit \n 1. Add an item \n 2. Display stock for an item \n 3. Discontinue an item"); 
      String choice = s.next(); 

      if(choice.equals("0")){ 
       System.out.println("Thank you for using the Sports Inventory Application. Good bye."); 
       condition = false; 
       System.exit(0); 
      } 
      else if(choice.equals("1")){ 
       store.addItem(); 
      } 
      else if(choice.equals("2")){ 
       System.out.println("Item Name: "); 
       itemName = s.nextLine(); 
       store.displayItem(itemName); 
      } 
      else if(choice.equals("3")){ 
       System.out.println("Item Name: "); 
       itemName = s.nextLine(); 
       store.deleteItem(itemName); 
      } 
     } 
     while(condition == true); 



    } 
} 

결과는

import java.util.ArrayList; 

import java.util.Scanner; 

public class Store { 
    private ArrayList<Item> inventory; 

    public Store(){ 
     inventory = new ArrayList<Item>(); 
    } 

public void addItem(){ 
    Item newItem; 
    int itemAmount; 
    String itemName; 
    Scanner input = new Scanner(System.in); 

    System.out.println("Item Name: "); 
    itemName = input.nextLine(); 
    System.out.println("Item Amount: "); 
    itemAmount = input.nextInt(); 

    newItem = new Item(itemName, itemAmount); 
    inventory.add(newItem); 

    System.out.println("Item added. Information: " + inventory.get(0)); 
    input.close(); 
} 

public void deleteItem(String itemName){ 
    int itemIndex; 
    Item itemToDelete; 

    itemToDelete = new Item(itemName); 
    itemIndex = inventory.indexOf(itemToDelete); 
    if(itemIndex > -1){ 
     inventory.remove(itemIndex); 
    } 
    else{ 
     System.out.println("Item does not exist."); 
    } 
} 
public void displayItem(String itemName){ 
    int itemIndex; 
    Item itemToDisplay, item; 

    itemToDisplay = new Item(itemName); 
    itemIndex = inventory.indexOf(itemToDisplay); 
    if (itemIndex > -1){ 
     item = inventory.get(itemIndex); 
     System.out.println(item); 
    } 
    else{ 
     System.out.println("Item does not exist."); 
    } 
    } 

} 

항목 클래스 : 당신은없이 Scanner.next()를 호출

public class Item { 
    private int itemAmount; 
    private String itemName; 

    public Item(String name, int amount){ 
     this.itemName = name; 
     this.itemAmount = amount; 
    } 
    public Item(String name){ 
     itemAmount = 0; 
     this.itemName = name; 
    } 

    public int getItemAmount(){ 
     return itemAmount; 
    } 
    public String getItemName(){ 
     return itemName; 
    } 
    public String getItem(){ 
     return itemName + itemAmount; 
    } 
    @Override 
    public String toString(){ 
     String itemString; 
     itemString = this.itemName + "\n"; 
     itemString += "Current amount in inventory is: " + this.itemAmount; 
     return itemString; 
    } 
} 
+2

모든 스택 추적? –

+0

java.util.NoSuchElementException java.util.Scanner.throwFor (Scanner.java:862) java.util.Scanner.next에서 \t (Scanner.java:1371) Inventory.main에서 \t (Inventory.java에서 \t : 24) – CoderPerson

+0

@SteveSmith 나는 그것을 포스트에 추가했다. – CoderPerson

답변

0

여기에 프로그램의 다른 클래스입니다 먼저 0123에 전화.

Scanner.next은 파일 끝에 도달했기 때문에 예외가 발생합니다. 거짓 Scanner.hasNext() 반환 (A while 루프를 사용하여 시작에서 확인합니다.) 때 루프를 종료한다

편집 : 당신은 방법 addItem()에 로컬로 선언 된 스캐너를 폐쇄했다. 이는 백킹 채널, 즉 표준 입력을 폐쇄하는 부작용을 갖는다. 따라서 메인 루프의 스캐너는 더 이상 입력을 얻을 수 없으며 닫힌 파일이 표시됩니다.

동일한 방법으로 열어 본 내용을 모두 닫으려면 좋겠지 만 표준 입력의 경우 응용 프로그램이 종료된다는 결론을 내릴 수 있습니다.

+0

스캐너가 파일을 읽지 않고 있지만 그 시간에 사용자로부터 더 많은 사용자 입력을 받아야하지만 입력을 묻는 대신 오류가 발생합니다 – CoderPerson

+0

재미 있습니다 . 스택 추적은 Scanner.next가 NoSuchElementException을 발생 시켰음을 보여줍니다. 이것은 파일의 끝에 도달 할 때 발생합니다. 이것은 Windows에서 control-Z를 입력하거나 Linux/MacOS에서 control-D를 입력하여 콘솔에서 알릴 수도 있습니다. 당신이 그 통제 문자 중 하나를 입력하지 않았다고 확신합니까? –

+0

예, Scanner.nextLine 또는 Scanner.nextInt를 사용하여 시도했지만 동일한 오류가 발생합니다. 프로그램에 파일 사용이 없습니다. – CoderPerson

0

당신의 코드가 다수에게 Scanner 객체를 사용에 문제가 될 것으로 보인다는 는 하나의 Scanner 인스턴스를 정의하고 다음 코드를 통해 모두 사용 (: How to use multiple Scanner objects on System.in? 자세한 내용은이 대답을 확인)하려고합니다. indexOf를 호출 할 때

또한, 필수 Item 클래스의 equalshashCode 최우선을 놓친 올바른 개체를 검색 할하려는 경우 :

그래서 내가 여기에 나를 위해 잘 작동 버전을 게시 할 것입니다 :

Store 클래스 :

public class Store { 
    private ArrayList<Item> inventory; 

    public Store(){ 
     inventory = new ArrayList<>(); 
    } 

    public void addItem(Scanner input){ 
     Item newItem; 
     int itemAmount; 
     String itemName; 

     System.out.println("Item Name: "); 
     itemName = input.nextLine(); 
     System.out.println("Item Amount: "); 
     itemAmount = Integer.parseInt(input.nextLine()); 

     newItem = new Item(itemName, itemAmount); 
     inventory.add(newItem); 

     System.out.println("Item added. Information: " + inventory.get(0)); 
    } 

    public void deleteItem(String itemName){ 
     int itemIndex; 
     Item itemToDelete; 

     itemToDelete = new Item(itemName); 
     itemIndex = inventory.indexOf(itemToDelete); 
     if(itemIndex > -1){ 
      inventory.remove(itemIndex); 
     } 
     else{ 
      System.out.println("Item does not exist."); 
     } 
    } 
    public void displayItem(String itemName){ 
     int itemIndex; 
     Item itemToDisplay, item; 

     itemToDisplay = new Item(itemName); 
     itemIndex = inventory.indexOf(itemToDisplay); 
     if (itemIndex > -1){ 
      item = inventory.get(itemIndex); 
      System.out.println(item); 
     } 
     else{ 
      System.out.println("Item does not exist."); 
     } 
    } 

} 

Item 클래스 :

public class Item { 
    private int itemAmount; 
    private String itemName; 

    public Item(String name, int amount){ 
     this.itemName = name; 
     this.itemAmount = amount; 
    } 
    public Item(String name){ 
     itemAmount = 0; 
     this.itemName = name; 
    } 

    public int getItemAmount(){ 
     return itemAmount; 
    } 
    public String getItemName(){ 
     return itemName; 
    } 
    public String getItem(){ 
     return itemName + itemAmount; 
    } 

    @Override 
    public String toString(){ 
     String itemString; 
     itemString = this.itemName + "\n"; 
     itemString += "Current amount in inventory is: " + this.itemAmount; 
     return itemString; 
    } 

    @Override 
    public boolean equals(Object o) { 
     if (this == o) return true; 
     if (!(o instanceof Item)) return false; 

     Item item = (Item) o; 

     return itemName.equals(item.itemName); 

    } 

    @Override 
    public int hashCode() { 
     return itemName.hashCode(); 
    } 

Inventory 클래스 :

public class Inventory { 
    public static void main(String[] args) { 
     Store store = new Store(); 
     String itemName; 

     System.out.println("Welcome to the Inventory Application. You can add an item, display the stock for an item, or discontinue an item."); 
     boolean condition = true; 
     Scanner s = new Scanner(System.in); 
     do { 
      System.out.println("Please select an option and type the option number." + "\n 0. Quit \n 1. Add an item \n 2. Display stock for an item \n 3. Discontinue an item"); 
      String choice = s.nextLine(); 

      if (choice.equals("0")) { 
       System.out.println("Thank you for using the Sports Inventory Application. Good bye."); 
       condition = false; 
       System.exit(0); 
      } else if (choice.equals("1")) { 
       store.addItem(s); 
      } else if (choice.equals("2")) { 
       System.out.println("Item Name: "); 
       itemName = s.nextLine(); 
       store.displayItem(itemName); 
      } else if (choice.equals("3")) { 
       System.out.println("Item Name: "); 
       itemName = s.nextLine(); 
       store.deleteItem(itemName); 
      } 
     } 
     while (condition == true); 


    } 
} 
관련 문제