【发布时间】:2017-08-19 14:54:50
【问题描述】:
以下代码要求用户输入他消费的物品的描述、价格和数量。
有一个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()) } -
最后一个
for循环可以是for (Gastos bill : billArr) {
标签: java loops arraylist while-loop switch-statement