So I have a text file that looks like this
所以我有一个看起来像这样的文本文件
4
10 orange
20 grape
100 Pencil Cases
4 Card
The first line is the number of objects. The next lines are the price and the name of the object. I have to find the object with the lowest price and return only the name of the object. (So, in this case "Card")
第一行是对象的数量。下一行是价格和对象的名称。我必须找到价格最低的对象,并只返回对象的名称。 (所以,在这种情况下“卡”)
I put the txt into an Arraylist and split it so I could only get the numbers. I am trying to put the numbers into a new integer array to compare them. And this is the code I've tried.
我将txt放入Arraylist并拆分它,所以我只能得到数字。我试图将数字放入一个新的整数数组来比较它们。这是我尝试过的代码。
public class Assignment {
public static void main(String[] args) {
try {
BufferedReader rd = new BufferedReader(new FileReader("C:\\Users\\USER\\Documents\\input.txt"));
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = rd.readLine()) != null)
{
lines.add(line);
}
rd.close();
for (int i =0; i<lines.size(); i++) {
String[] items = lines.get(i).split(" ", 2);
for (String s: items) {
System.out.println(s);
}
int[] array2 = new int[items.length];
int k =0;
for (int n= 2; n< items.length; n=n+2) {
array2[k] = Integer.parseInt(items[n]);
for (Integer l: array2) {
System.out.println(l); }
}
}
}
catch (Exception e) {
System.out.println("Error");
}
}
}
I think something is wrong with the array2 part. Can someone give a hint on how I should fix this?? New to * and Java so I'm sorry if there is a problem with my question(or my grammar too...)!
我认为array2部分有问题。有人可以暗示我应该如何解决这个问题? *和Java的新手,所以如果我的问题(或我的语法也有问题)我很抱歉!
1 个解决方案
#1
3
I am trying to put the numbers into a new integer array to compare them
我试图将数字放入一个新的整数数组来比较它们
Here's how you can do it.
这是你如何做到的。
int[] array2 = new int[lines.size() - 1];
int k = 0;
for (int i = 1; i < lines.size(); i++) { //Start at row 1
String[] items = lines.get(i).split(" ", 2);
array2[k++] = Integer.parseInt(items[0]); //The first element is the price
}
System.out.println(Arrays.toString(array2)); //[10, 20, 100, 4]
But, with this, you cannot get the name of the item with the maximum price. So, you need to store both the name and the price together which I'll leave it to you.
但是,有了这个,您无法获得具有最高价格的项目名称。因此,您需要同时存储名称和价格,我将留给您。
#1
3
I am trying to put the numbers into a new integer array to compare them
我试图将数字放入一个新的整数数组来比较它们
Here's how you can do it.
这是你如何做到的。
int[] array2 = new int[lines.size() - 1];
int k = 0;
for (int i = 1; i < lines.size(); i++) { //Start at row 1
String[] items = lines.get(i).split(" ", 2);
array2[k++] = Integer.parseInt(items[0]); //The first element is the price
}
System.out.println(Arrays.toString(array2)); //[10, 20, 100, 4]
But, with this, you cannot get the name of the item with the maximum price. So, you need to store both the name and the price together which I'll leave it to you.
但是,有了这个,您无法获得具有最高价格的项目名称。因此,您需要同时存储名称和价格,我将留给您。