gpt4 book ai didi

java - 礼品登记循环程序

转载 作者:行者123 更新时间:2023-11-29 03:39:40 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,用于在礼品注册表中进行输入。用户可以输入所需数量的礼品以及可以购买的商店。一旦用户表示希望停止输入新商品,将显示所有礼品商品和商店的摘要。

这些是我当前的代码:

import java.util.*;
public class GiftRegistry
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);

List<GiftRegistry> list = new ArrayList<GiftRegistry>();
private String item;
private String store;
char ans;

System.out.print("Do you wish to make a gift registry? (y/n) ");
ans = input.nextLine().charAt(0);

while (ans != 'n')
{
GiftRegistry object = new GiftRegistry();
System.out.print("Enter item: ");
object.setItem(input.nextLine());
System.out.print("Enter store: ");
object.setStore(input.nextLine());
System.out.print("Any more items? (y/n) ");
ans = input.nextLine().charAt(0);
list.add(object);
}

System.out.println("Gift Registry");
for (GiftRegistry myObject : list) {
System.out.print(myObject.getItem()+" - "+myObject.getStore());
System.out.println();
}
}

这是当前输入

Do you wish to make a gift registry? (y/n) y
Enter item: laptop
Enter store: Acer
Any more items? (y/n) y
Enter item: watch
Enter store: Swatch
Any more items? (y/n) n

它应该像这样输出:

Gift Registry
laptop - Acer
watch - Swatch

谁能帮我得到正确的输出谢谢

最佳答案

您可以创建自定义对象来保存您的值 -

class MyObject {
private String item;
private String Store;

<getter & setters>

}

并将用户输入数据添加到列表中。

List<MyObject> list = new ArrayList<MyObject>();
...
while (ans != 'n') {
MyObject object = new MyObject();
System.out.print("Enter item: ");
object.setItem(input.nextLine());
System.out.print("Enter store: ");
object.setStore(input.nextLine());
System.out.print("Any more items? (y/n) ");
ans = input.nextLine().charAt(0);
list.add(object);
}

正确的打印方式是——

System.out.println("Gift Registry");
for (MyObject myObject : list) {
System.out.print(myObject.getItem()+" - "+myObject.getStore());
System.out.println();
}

输出将是 -

Gift Registry
laptop - Acer
watch - Swatch

关于java - 礼品登记循环程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13762094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com