How do I put certain elements(String) in Array into a new array(Integer)?

Jisoo Source

So I have a text file that looks like this

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.

 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) 
              for (int i =0; i<lines.size(); i++) {
                String[] items = lines.get(i).split(" ", 2);
                for (String s: items) {

                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) {

I think something is wrong with the array2 part. Can someone give a hint on how I should fix this?? New to stackoverflow and Java so I'm sorry if there is a problem with my question(or my grammar too...)!



answered 3 months ago user7 #1

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.

comments powered by Disqus