【发布时间】:2016-04-24 07:53:19
【问题描述】:
我的程序应该询问用户姓名、价格以及他想要的数量,直到他按下“x”。此时程序应该打印收据。
- 如何在不知道用户想要购买多少商品的情况下保存所有用户输入?
- 我正在使用三个类。我不知道如何将 Main-class 的名称、数量、价格赋予 Eintrag 类。
如何从主要的 Kassenzettel 类中调用列表以供我打印?
另外,我重写了 to String 方法,将我的收据设置为“类似超市”,这种格式是否会应用到主类中?
这是我的主要课程:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.println("What would you like? ");
String produkt = scanner.nextLine();
System.out.println("How many pieces do you want?");
int anzahl = scanner.nextInt();
System.out.println("How much does " + produkt + "cost?");
double preis = scanner.nextDouble();
//Im not even sure if that should be there
Kassenzettel list =new Kassenzettel();
Eintrag carrots = new Eintrag("carrots", 5, 0.40);
Kassenzettel.add(carrots);
System.out.println("__________________________________");
System.out.println(" IHRE RECHNUNG ");
System.out.println("__________________________________");
}
}
我的 Eintrag 级:
public class Eintrag {
private String produkt;
private double preis;
private int anzahl;
public Eintrag(String produkt, int anzahl, double preis) {
this.anzahl=anzahl;
this.produkt=produkt;
this.preis=preis;
}
public int getAnzahl(){
return this.anzahl;
}
public double getPreis(){
return this.preis * this.anzahl;
}
public String getProdukt() {
return this.produkt;
}
public void setAnzahl(int anzahl) {
this.anzahl = anzahl;
}
public String toString() {
return (String.format("%-9s %2d x %5.2f EUR",produkt , anzahl, preis
+ "%30.2f EUR", anzahl * preis));
}
}
我的 Kassenzettel 类,它应该包含一个 Eintrag 对象列表 导入 java.util.ArrayList;
public class Kassenzettel {
private static ArrayList<Eintrag> kassenZettel;
private double summe;
// Constructs a new empty grocery list.
public static void add(Eintrag item) {
kassenZettel.add(item);
}
@Override
public String toString() {
return (String.format("%-9s %2d x %5.2f EUR",kassenZettel
+ "%30.2f EUR"
+ "SUMME", summe));
}
}
【问题讨论】:
-
“我如何在不知道他想购买多少商品的情况下保存所有用户输入?” - 要么使用某种
List,它可以动态增长并保持循环,直到用户输入一些退出条件(“想要购买更多东西?”)或提前询问用户他们想要购买的商品数量(并且只循环多次) -
“我正在使用三个类。我不知道如何将 Main-class 的名称、数量、价格提供给 Eintrag 类。” - Passing Information to a Method or a Constructor
-
“另外,我重写了 to String 方法,为了让我的收据“类似于超市”,这种格式会在主类中应用吗?”- 所以只要打印它的人使用
toString方法(即System.out.println(instanceOfKassenzettel) -
“我如何在主类中调用 Kassenzettel 类的列表以便我打印?” 提供某种访问器方法,即
Kassenzettel#getItems返回List(或List的副本或不可修改版本)-Controlling Access to Members of a Class -
这是个好主意,你能帮我处理一下循环吗?我真的不知道我会从哪里开始