回答編集履歴

1

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

2021/04/24 16:00

投稿

kazuma-s
kazuma-s

スコア8224

test CHANGED
@@ -25,3 +25,149 @@
25
25
  ```
26
26
 
27
27
  for の中で iListData を毎回上書きしているから、iList の最後のデータしか入りませんよ。
28
+
29
+
30
+
31
+ **追記**
32
+
33
+ for 文で単純代入するから上書きになるのです。
34
+
35
+ += でどんどん繋いでいけばよいでしょう。
36
+
37
+ "\n" を挟んで連結することにしました。
38
+
39
+ 質問のコードは Item や inputuser が未定義なので、適当に補いました。
40
+
41
+ ```Java
42
+
43
+ import java.io.*; // BufferedReader, InputStreamReader, IOException
44
+
45
+ import java.util.*; // List, ArrayList
46
+
47
+
48
+
49
+ class Main {
50
+
51
+ public static void main(String[] args) throws IOException {
52
+
53
+ Item iList01 = new Item("01", "desk", 5000);
54
+
55
+ Item iList02 = new Item("02", "pen", 1000);
56
+
57
+ ArrayList<Item> itemList = new ArrayList<>(); // ★ <Item>
58
+
59
+ itemList.add(iList01);
60
+
61
+ itemList.add(iList02);
62
+
63
+ BufferedReader inputuser = new BufferedReader( // ★ inputuser
64
+
65
+ new InputStreamReader(System.in));
66
+
67
+
68
+
69
+ while (true) {
70
+
71
+ System.out.println("1.一覧表示");
72
+
73
+ String inputSelectMenuNo = inputuser.readLine();
74
+
75
+ if (inputSelectMenuNo.equals("1")){
76
+
77
+ ShowItems showitems = new ShowItems(itemList);
78
+
79
+ showitems.ShowItem();
80
+
81
+ }
82
+
83
+ }
84
+
85
+ }
86
+
87
+ }
88
+
89
+
90
+
91
+ class ShowItems {
92
+
93
+ private List<Item> itemList;
94
+
95
+
96
+
97
+ public ShowItems(ArrayList<Item> itemList ) {
98
+
99
+ this.itemList = itemList;
100
+
101
+ }
102
+
103
+
104
+
105
+ public void ShowItem() {
106
+
107
+ ProductsDisplay selectProductDisplay = new ProductsDisplay(itemList);
108
+
109
+ String showDisplay = selectProductDisplay.productsDisplay();
110
+
111
+ System.out.println(showDisplay);
112
+
113
+ }
114
+
115
+ }
116
+
117
+
118
+
119
+ class ProductsDisplay {
120
+
121
+ private List<Item> iList;
122
+
123
+
124
+
125
+ public ProductsDisplay(List<Item> paramItemList){
126
+
127
+ this.iList = paramItemList;
128
+
129
+ }
130
+
131
+
132
+
133
+ public String productsDisplay() {
134
+
135
+ String iListData = "";
136
+
137
+ for (Item i : this.iList) {
138
+
139
+ iListData += i.getItemCode() + "," // ★ +=
140
+
141
+ + i.getItemName() + "," + i.getPrice() + "\n"; // ★ "\n"
142
+
143
+ }
144
+
145
+ return iListData;
146
+
147
+ }
148
+
149
+ }
150
+
151
+
152
+
153
+ class Item { // ★ Item
154
+
155
+ String code, name; int price;
156
+
157
+
158
+
159
+ Item(String code, String name, int price) {
160
+
161
+ this.code = code; this.name = name; this.price = price;
162
+
163
+ }
164
+
165
+ String getItemCode() { return code; }
166
+
167
+ String getItemName() { return name; }
168
+
169
+ int getPrice() { return price; }
170
+
171
+ }
172
+
173
+ ```