2017-03-27 1 views
2

다음 코드는 사용자가 소비 한 품목의 설명, 가격 및 수량을 입력하도록 요청합니다.while 루프가 적절하게 작동하지 않음

더 많은 항목을 입력 할 것인지 묻는 while 루프가 있습니다. 그가하는 경우에, 프로그램은 다른 품목의 다른 묘사, 가격 및 양, 등등을 삽입하도록 요청합니다.

더 많은 항목을 입력하지 않으려는 경우 출력은 그가 배열에 추가 한 모든 항목과 청구서의 합계입니다.

문제는 : 처음 실행하는 동안 작동하지만 두 번째로 사용자가 "y"로 응답하면 설명에서 오른쪽으로 가격이 올라간 것처럼 오류를 반환합니다 목. 사용자가 설명을 입력하면 입력 불일치 예외가 발생합니다.

메인 클래스 :

package com.company; 

import java.util.ArrayList; 
import java.util.Scanner; 

public class Main { 

public static void main(String[] args) { 

    ArrayList<Gastos> billArr = new ArrayList<>(); 
    Scanner input = new Scanner(System.in); 
    int qntItems = 0 , counter = 0; 
    String ans; 
    Gastos bill = new Gastos(); 

    while (qntItems == 0) { 

     System.out.print("Want to input another item? Y/N: "); 
     ans = input.nextLine(); 

     switch (ans){ 
      case "y": 
       qntItems = 0; 
       bill.setDescription(); 
       bill.setPrice(); 
       bill.setQuantity(); 
       bill.getTotal(); 
       billArr.add(bill); 

       counter = counter + 1; 
       break; 

      case "n": qntItems = 1; 
        break; 
      default: System.out.print("Invalid!"); 
         System.out.println(); 
         break; 
     } 
     input.close(); 

    } 
    for (int i = 0; i < billArr.size();i++){ 
     System.out.print(bill.getDescription() + ", " + bill.getPrice() + ", " + bill.getQuantity() + ", " + "the total is: " + bill.getTotal()); 
    } 

} 
} 

과 Gastos 클래스 :

package com.company; 

import java.util.Scanner; 

public class Gastos { 

private String description; 
private double price, quantity, total; 
private Scanner input = new Scanner(System.in); 

public void setDescription(){ 
    System.out.print("Insert the item name: "); 
    description = input.nextLine(); 
} 

public void setPrice(){ 
    System.out.print("insert the item price: "); 
    price = input.nextDouble(); 
} 

public void setQuantity(){ 

    System.out.print("Insert the quantity: "); 
    quantity = input.nextDouble(); 
} 

public String getDescription(){ 
    return description; 
} 

public double getPrice() { 
    return price; 
} 

public double getQuantity() { 
    return quantity; 
} 

public double getTotal(){ 
    total = price * quantity; 
    return total; 
} 

} 

가 어떻게이 오류를 처리 할 수 ​​있습니까?

+2

두 번째 루프를 자세히 살펴보십시오. 'System.out.print (billArr.get (i) .getDescription() .....'또는 단순히 다음을 넣어야합니다 : for (Gastos b : billArr) {System.out.print (b.getDescription())}}' – zengr

+0

마지막'for' 루프는'for (Gastos bill : billArr) {' – 4castle

답변

3

두 번째 루프에 버그가 있습니다.

그것은해야한다 : System.out.print(billArr.get(i).getDescription()..... 하거나 넣어 :

for(Gastos b : billArr){ 
    System.out.print(b.getDescription()) 
} 

업데이트 1 : 또 다른 오류가 첫 번째 루프의 끝에서 Scanner을 닫으입니다. 루프 외부 또는 case "n" 내부로 input.close();을 이동하십시오.

업데이트 2 : 다른 문제가 발생하면 새로운 세부 정보를 입력 할 때마다 Gastos을 다시 초기화해야합니다. 따라서 case "y": 바로 뒤에 Gastos bill = new Gastos();을하고 while 루프 전에 초기화 할 위치에서 제거해야합니다. 귀하의 메인은 다음과 같아야합니다 :

public static void main(String[] args) { 

    ArrayList<Gastos> billArr = new ArrayList<>(); 
    Scanner input = new Scanner(System.in); 
    int qntItems = 0 , counter = 0; 
    String ans; 

    while (qntItems == 0) { 

     System.out.print("Want to input another item? Y/N: "); 
     ans = input.nextLine(); 

     switch (ans){ 
      case "y": 
       Gastos bill = new Gastos(); 
       qntItems = 0; 
       bill.setDescription(); 
       bill.setPrice(); 
       bill.setQuantity(); 
       bill.getTotal(); 
       billArr.add(bill); 

       counter = counter + 1; 
       break; 

      case "n": qntItems = 1; 
       input.close(); 
       break; 
      default: System.out.print("Invalid!"); 
       System.out.println(); 
       break; 
     } 
    } 
    for (Gastos bill : billArr){ 
     System.out.print(bill.getDescription() + ", " + bill.getPrice() + ", " + bill.getQuantity() + ", " + "the total is: " + bill.getTotal()); 
    } 
} 

나는 언젠가는 디버깅을하고 자바의 오브젝트가 어떻게 작동하는지 이해해야한다고 생각합니다. 이것들은 쉽게 잡힐 수있는 기본적인 오류입니다.

+0

이 될 수 있습니다. 실제로 두 번째 루프가 작동합니다! 두 번째로'while (qntItems == 0) {' – RooseveltJr

+0

무엇이 오류입니까? – zengr

+0

콘솔에 다음과 같은 메시지가 나타납니다. '다른 항목을 입력 하시겠습니까? Y/N : y 항목 이름을 삽입하십시오 : 항목 가격을 삽입하십시오 :'가격이 설명을 덮어 쓴 것처럼 . 설명을 삽입하면'java.util.InputMismatchException'이 발생합니다. – RooseveltJr

관련 문제