2015-01-02 3 views
1

저는 초보자 자바 프로그래머입니다. 사용자가 이름, 수량 및 질량을 입력하여 Fruit 객체를 만들 수있는 프로그램을 만들려고했습니다. 나는 생성자와 함께 별도의 과일 수업을했다. 사용자가 이름을 입력하도록 요청하면 모든 것이 잘되지만 수량/질량에 도달하면 java.util.NoSuchElementException 런타임 오류가 발생합니다. java.util.NoSuchElementException 오류?

내 코드

public class Fruit { 

    String Name; 
    int Quantity; 
    double Mass; 

    public Fruit (String Name, int Quantity, double Mass){ 
     this.Name = Name; 
     this.Quantity = Quantity; 
     this.Mass = Mass; 
    } 

    public void Information(){ 
     System.out.println("This fruit is an " + Name + " and there's " + Quantity + " of it"); 
    } 
} 

import java.util.Scanner; 

public class Fruits { 

    public static void main (String[] args){ 

     Fruit Apple = new Fruit("Apple", 5, 32.6); 
     System.out.println (Apple.Name); 

      System.out.println("What would you like to name the fruit?: "); 
      Scanner name1 = new Scanner (System.in); 
      String name = name1.nextLine(); 
      name1.close(); 

      System.out.println("How much fruits are there?: "); 
      Scanner quant1 = new Scanner (System.in); 
      int quantity = quant1.nextInt(); 
      quant1.close(); 

      System.out.println("What is the mass of the Fruit?: "); 
      Scanner mass1 = new Scanner (System.in); 
      double mass = mass1.nextDouble(); 
      mass1.close(); 

      Fruit newFruit = new Fruit (name, quantity, mass); 

      newFruit.Information(); 

    } 
} 
+1

스캐너를 닫으면 기본 'System.in' 스트림도 닫습니다. 하나의 Scanner 인스턴스 만 사용하고 완료하면 모든 인스턴스를 닫아 입력을 모두 제공하십시오. –

+0

또한 Java 코딩 표준을 따르려면 변수가 소문자 여야합니다. ('Name'은'name'이어야하고, Quantity는'quantity' 등이어야합니다.) – mbomb007

답변

0

여러 스캐너 개체를 만들 필요가 없습니다 것입니다. 첫 번째 스캐너를 닫을 때 실제로는 System.in이 닫힙니다. 그래서 두 번째 요소는 System.in을 얻을 수 없습니다. 따라서 모든 입력 검색에 단일 스캐너를 사용하는 것이 더 좋습니다.

 Scanner scanner = new Scanner (System.in); 
     System.out.println("What would you like to name the fruit?: "); 
     String name = scanner.nextLine(); 
     System.out.println("How much fruits are there?: "); 
     int quantity = scanner.nextInt(); 
     System.out.println("What is the mass of the Fruit?: "); 
     double mass = scanner.nextDouble(); 
관련 문제