다음 코드는 사용자가 소비 한 품목의 설명, 가격 및 수량을 입력하도록 요청합니다.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;
}
}
가 어떻게이 오류를 처리 할 수 있습니까?
두 번째 루프를 자세히 살펴보십시오. 'System.out.print (billArr.get (i) .getDescription() .....'또는 단순히 다음을 넣어야합니다 : for (Gastos b : billArr) {System.out.print (b.getDescription())}}' – zengr
마지막'for' 루프는'for (Gastos bill : billArr) {' – 4castle