次のコードは、消費したアイテムの説明、価格、量を入力するようにユーザーに求めます。Whileループはそれに応じて動作しません
もっと多くの項目を入力したいかどうかを尋ねるwhileループがあります。もしそうであれば、プログラムは別の説明、他の品目の価格と数量などを挿入するよう求めます。
もっと多くの項目を入力したくない場合、出力は配列に追加したすべての項目と請求書の合計です。
問題は:whileが実行されて初めて動作しますが、ユーザーが "y"で答えると2回目に、説明の右から2番目の価格にジャンプしたようにエラーが返されます項目。ユーザーが説明を入力すると、入力ミスマッチ例外が発生します。
メインクラス:
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
最後の 'for'ループは' for(Gastos bill:billArr){' – 4castle