0

My .txt file is

code1,description1,price1
code2,description2,price2
etc.

Using:

ArrayList<String> items = new ArrayList<String>();
String description;
File fn = new File("file.txt");
String[] astring = new String[4];
try{
 Scanner readFile = new Scanner(fn);
 Scanner as = new Scanner(System.in);
 while (readFile.hasNext()){
  astring = readFile.nextLine().split(",");
  String code = astring[0];
  items.add(code);
  description = astring[1];
}
}catch(FileNotFoundException){
//
}

for(String things: items){
 System.out.println("The code is: " + things + "The description is " + description);
}

My output prints out

code1 description1
code2 description1
code3 description1

I'm trying to figure out how to make the description update as the code's do. e.g.

code1 description1
code2 description2
code3 description3

If this question has been asked already, I apologize. I couldn't find out how to do it by searching around but if there's a reference to figure this out I'll close this down and go there. Thanks in advance!

3
  • Your astring variable has an unnecessarily broad scope. Should be declared in the while loop Commented Dec 4, 2018 at 13:11
  • code is incrementing because you are iterating items, description not because it's not related to that array. Commented Dec 4, 2018 at 13:11
  • So how would I get the descriptions to update within items? Commented Dec 4, 2018 at 13:20

2 Answers 2

1

The problem is with your logic. You are storing only astring[0] to the items ArrayList and overwriting the value of description each time. As a result on last value read is stored in description which you are printing in the loop.

I prefer creating a custom class as follows. (Just for the sake of demo otherwise you would declare your fields as private and provide getters and setters)

class MyObject {
 public String code;
 public String description;
 public String price;
}

now instead of creating ArrayList of Strings you will create ArrayList of MyObject as follows

ArrayList<MyObject> items = new ArrayList<MyObject>();

now create a new instance of MyObject each time you read a line , populate its fields with the values from astring as follows

ArrayList<MyObject> items = new ArrayList<MyObject>();
    File fn = new File("test.txt");
    String[] astring = new String[4];
    try {
        Scanner readFile = new Scanner(fn);
        Scanner as = new Scanner(System.in);
        MyObject myObject;
        while (readFile.hasNext()) {
            astring = readFile.nextLine().split(",");
            myObject = new MyObject();

            myObject.code = astring[0];
            myObject.description  = astring[1];
            myObject.price = astring[2];

            items.add(myObject);

        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

and then finally print it using the same foreach loop as follows

for (MyObject item : items) {
        System.out.println("The code is: " + item.code + " The description is: " + item.description + " The price is: " + item.price);
    }

Output

The code is: code1 The description is: description1 The price is: price1
The code is: code2 The description is: description2 The price is: price2
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks alot! I was needing to refer from a class anyways so this is perfect.
@Auron Kelmud Glad to help
@Mehdi I promise I didn't copy your code. As soon as I was done composing my answer and hit submit I saw your answer already posted with identical solutions. It was pure coincidence
@SyedAhmedJamil my answer has posted 11 min before your answer! You just got the idea, refactored the code and then posted it.
@Mehdi I was on the composing my answer screen when meanwhile you posted your answer. I really didn't look at your answer until I submitted mine.
|
1

The reason you're seeing that output is that you are not saving description along with the code inside the list, that is why the last description is saved within the description variable not all description values.

To solve this problem, you can create a simple Java Bean/POJO class and wrap your data inside it and then you can simply fetch the value you have saved it and then show it properly. Take a look at the code below:

public class Launcher{
    public static void main(String[] args) {
        ArrayList<Item> items = new ArrayList<Item>();
        File fn = new File("file.txt");

        try {
            Scanner readFile = new Scanner(fn);
            while (readFile.hasNext()) {
                String[] astring = readFile.nextLine().split(",");
                String code = astring[0];
                String description = astring[1];
                String price = astring[2];
                Item item = new Item(code, description, price);
                items.add(item);

            }
        } catch (FileNotFoundException d) { // }

        }

        for (Item thing : items) {
            System.out.println(String.format("The code is: %s\tThe description is: %s\tThe Price is %s",thing.getCode(),thing.getDescription(), thing.getPrice()));
        }
    }
}

class Item {
    private String code;
    private String description;
    private String price;

    public Item(String code, String description, String price) {
        this.code = code;
        this.description = description;
        this.price = price;
    }

    public String getCode() {
        return code;
    }

    public String getDescription() {
        return description;
    }

    public String getPrice() {
        return price;
    }
}

1 Comment

Thanks alot! This works like a charm and is exactly what I was trying to accomplish.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.