好的,这是对我要写的内容的解释:
getBreadInfo
- 将bread.txt读入数组列表(包含面包)
name,$和price)然后分配给一个数组breadInfo []
为SandwichApp返回此数组以显示面包菜单。getBread
- 类似于getBreadInfo,除了它只包含
面包名称,并为SandwichApp返回另一个数组bread []
用户选择哪个面包因为用户输入了一个数字
与面包(索引+ 1)相关联,而不是面包名称。getMapBreadPrice
- 与上面两个类似,只是它返回一个
包含面包名称(键)和价格(值)的对值的哈希映射
为SandwichApp找出面包用户的价格
地选择。这就是我写的。只是想知道这是否正确?
public class SandwichDB {
private ArrayList<String> breadsList = null;
public String[] getBreadInfo()
{
breadsList = new ArrayList<>();
try (BufferedReader in =
new BufferedReader(
new FileReader("bread.txt")))
{
String line = in.readLine();
while (line != null)
{
String[] elems = line.split("~");
breadsList.add(elems[0]+ " $" + elems[1]);
}
}
catch(IOException e)
{
System.out.println(e);
return null;
}
String[] breadInfo = breadsList.toArray(new String[]{});
return breadInfo;
}
public String[] getBread()
{
breadsList = new ArrayList<>();
try (BufferedReader in =
new BufferedReader(
new FileReader("bread.txt")))
{
String line = in.readLine();
while (line != null)
{
String[] elems = line.split("~");
breadsList.add(elems[0]);
}
}
catch(IOException e)
{
System.out.println(e);
return null;
}
String[] bread = breadsList.toArray(new String[]{});
return bread;
}
public HashMap<String, String> getMapBreadPrice()
{
HashMap<String, String> mapBreadPrice = new HashMap<>();
String line, elems[];
try
{
FileReader fr = new FileReader("bread.txt");
BufferedReader br = new BufferedReader(fr);
while ((line=br.readLine()) != null)
{
elems = line.split("~");
mapBreadPrice.put(elems[0], elems[1]);
}
}
catch(IOException e)
{
System.out.println(e);
return null;
}
return mapBreadPrice;
}
}
答案 0 :(得分:0)
第一个readLine
位于while
之前,因此不会重复。因此,虽然没有结束。
for (;;) {
String line = in.readLine();
if (line == null) {
break;
}
答案 1 :(得分:0)
为了构建3个结构,您似乎正在读同一个文件3次。您应该通过一次读取文件来构建数据结构。