0

I'm trying to get the information from Stock.txt and to transfer it into an array of strings, each index being a new line in the file. I get a warning:

Duplicate local variable. What is the problem, is it out of scope?

public static List<String> getStock(List<String> stockText){
    Scanner scanner = null;
    try {
        File input = new File("Stock.txt");
        scanner = new Scanner(input);
        String[] info = null;
        while (scanner.hasNextLine()) {
            info = scanner.nextLine().split(",");
        }
        List<String> stockText = Arrays.asList(info);
    }   catch (Exception e) {
        e.printStackTrace();
        System.out.println(e.getMessage());
    }
    finally {
        scanner.close();
    }
    return stockText;
}

}

4
  • 1
    stockText is the name of your input parameter and the local variable you create inside the try block Commented Apr 23, 2020 at 11:31
  • 1
    You're passing stockText as a parameter to the method and then create another local variable with the same name. You never use the paremeter so you can remove it from the declaration. Commented Apr 23, 2020 at 11:31
  • Did you try creating object of scanner class i.e. Scanner input = new Scanner(input); Commented Apr 23, 2020 at 11:32
  • Thank you all for the input, I understand the problem now! :) Commented Apr 23, 2020 at 11:36

1 Answer 1

3

As it is, stockText is an argument and later you create a variable with the same name. That's not allowed. If your intention was to use the same variable, remove List<String> from List<String> stockText = Arrays.asList(info);

Otherwise, give the variable another name.

Sign up to request clarification or add additional context in comments.

2 Comments

Even better would be to remove the method parameter as it is never used. Just create a List inside of the function and then return it.
@Amongalen I usually don't make suggestions of this type because many codes posted in SO are minimized, and there might be some residues of the original code that don't make sense in the minimized version, but is important in the full version.

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.