teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

for の中身の修正方法を追加

2021/04/24 16:00

投稿

kazuma-s
kazuma-s

スコア8222

answer CHANGED
@@ -11,4 +11,77 @@
11
11
  for(Item i : this.iList){
12
12
  iListData = (i.getItemCode() + "," + i.getItemName()+ "," + i.getPrice());
13
13
  ```
14
- for の中で iListData を毎回上書きしているから、iList の最後のデータしか入りませんよ。
14
+ for の中で iListData を毎回上書きしているから、iList の最後のデータしか入りませんよ。
15
+
16
+ **追記**
17
+ for 文で単純代入するから上書きになるのです。
18
+ += でどんどん繋いでいけばよいでしょう。
19
+ "\n" を挟んで連結することにしました。
20
+ 質問のコードは Item や inputuser が未定義なので、適当に補いました。
21
+ ```Java
22
+ import java.io.*; // BufferedReader, InputStreamReader, IOException
23
+ import java.util.*; // List, ArrayList
24
+
25
+ class Main {
26
+ public static void main(String[] args) throws IOException {
27
+ Item iList01 = new Item("01", "desk", 5000);
28
+ Item iList02 = new Item("02", "pen", 1000);
29
+ ArrayList<Item> itemList = new ArrayList<>(); // ★ <Item>
30
+ itemList.add(iList01);
31
+ itemList.add(iList02);
32
+ BufferedReader inputuser = new BufferedReader( // ★ inputuser
33
+ new InputStreamReader(System.in));
34
+
35
+ while (true) {
36
+ System.out.println("1.一覧表示");
37
+ String inputSelectMenuNo = inputuser.readLine();
38
+ if (inputSelectMenuNo.equals("1")){
39
+ ShowItems showitems = new ShowItems(itemList);
40
+ showitems.ShowItem();
41
+ }
42
+ }
43
+ }
44
+ }
45
+
46
+ class ShowItems {
47
+ private List<Item> itemList;
48
+
49
+ public ShowItems(ArrayList<Item> itemList ) {
50
+ this.itemList = itemList;
51
+ }
52
+
53
+ public void ShowItem() {
54
+ ProductsDisplay selectProductDisplay = new ProductsDisplay(itemList);
55
+ String showDisplay = selectProductDisplay.productsDisplay();
56
+ System.out.println(showDisplay);
57
+ }
58
+ }
59
+
60
+ class ProductsDisplay {
61
+ private List<Item> iList;
62
+
63
+ public ProductsDisplay(List<Item> paramItemList){
64
+ this.iList = paramItemList;
65
+ }
66
+
67
+ public String productsDisplay() {
68
+ String iListData = "";
69
+ for (Item i : this.iList) {
70
+ iListData += i.getItemCode() + "," // ★ +=
71
+ + i.getItemName() + "," + i.getPrice() + "\n"; // ★ "\n"
72
+ }
73
+ return iListData;
74
+ }
75
+ }
76
+
77
+ class Item { // ★ Item
78
+ String code, name; int price;
79
+
80
+ Item(String code, String name, int price) {
81
+ this.code = code; this.name = name; this.price = price;
82
+ }
83
+ String getItemCode() { return code; }
84
+ String getItemName() { return name; }
85
+ int getPrice() { return price; }
86
+ }
87
+ ```