2017-11-28 1 views
-1

수업 용 인벤토리 프로그램을 만들고 있습니다. Item 클래스, ArrayList가있는 Inventory 클래스 및 Inventory 테스터 클래스가 있습니다. 인벤토리에 추가 할 항목 수를 물어보고 매개 변수를 기반으로 항목을 추가하고 싶습니다. 이것은 내가 가지고 있지만 작동하지 않습니다 :사용자 입력을 기반으로 ArrayList에 대한 항목을 만드는 방법

import java.util.Scanner; 

public class InventoryTester 
{ 
    public static void main(String[] args) 
    { 
    Scanner input = new Scanner(System.in); 

    Inventory myInventory = new Inventory(); 

    System.out.println("Enter 1 to print all inventory data"); 
    System.out.println("Enter 2 to add items to the inventory"); 
    System.out.println("Enter 3 to "); 
    System.out.println("Enter 4 to "); 
    int choice = input.nextInt(); 

    if (choice == 1) 
    { 
     myInventory.printAllData(); 
    } 

    else if (choice == 2) 
    { 
     System.out.println("How many items are you adding?"); 
     int numOfItemsToAdd = input.nextInt(); 


     for (int i = 0; i < numOfItemsToAdd; i++) 
     { 
     System.out.println("Enter the name of item " + i); 
     input.nextLine(); 
     String tempName = input.nextLine(); 
     System.out.println("Enter the type of item " + i); 
     String tempType = input.nextLine(); 
     System.out.println("Enter the price of item " + i); 
     double tempPrice = input.nextInt(); 

     Item newItem = new Item(tempName, tempType, tempPrice); 
     myInventory.addItem(newItem); 
     } 
    } 
    input.close(); 
    } 
} 

EDIT : 실제로 내 문제는 아니었다. 나는이 조각이 작동하도록했다.

+0

내가 어떤 목록을 볼 수 없습니다 ... –

+0

매번 당신이 .nextInt()를 사용, 함수는 사용자 입력을 수집합니다. 따라서 input.nextInt()를 한 번 사용하고 그 값을 변수에 저장해야합니다. 변수의 값이 1 또는 2인지 확인 (모두 인쇄 또는 항목 추가) – Solace

+0

방금 ​​조금 변경했습니다. – user9022958

답변

0

nextInt()와 nextLine()을 함께 사용하는 경우 nextLine()을 호출하기 전에 마지막 줄 문자를 사용해야합니다. 그래서 당신과 같이 루프에 대한 귀하의 전() 추가 .nextLine을 추가해야합니다

int numOfItemsToAdd = input.nextInt(); 

input.nextLine(); //ADDED CODE 

    for (int i = 0; i <= numOfItemsToAdd; i++) 
    { 
    System.out.println("Enter the name of item " + i + 1); 
    String tempName = input.nextLine(); 
    System.out.println("Enter the type of item " + i + 1); 
    String tempType = input.nextLine(); 
    System.out.println("Enter the price of item " + i + 1); 
    double tempPrice = input.nextInt(); 

    Item newItem = new Item(tempName, tempType, tempPrice); 

    myInventory.addItem(newItem); 
    } 
관련 문제