user3019431
user3019431

Reputation: 11

List cannot be resolved

Hey I'm having an error "list cannot be resolved". Here is my code:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Objects {

    void inputData() {

        Objects object = new Objects();
        DaneTeleadresowe daneTeleadresowe = new DaneTeleadresowe();

        Scanner scanner1 = new Scanner(System.in);
        int ilu = scanner1.nextInt();

        Scanner scanner2 = new Scanner(System.in);

        List<String> list = new ArrayList<String>();

        for (int y=0; y<ilu; y++){
    for(int i=0;i<dataOfSomeSort.tableOfNames.length;  i++){
        System.out.println(dataOfSomeSort.tableOfNames[i]);
        String inputedData = scanner2.nextLine();
        list.add(inputedData);
    }   
}

    void showData(){

        Scanner scanner3 = new Scanner(System.in);
        int number = scanner3.nextInt();

        if(number < 1) {
            System.out.println("Wrong number.");
        } else if(number>1) {
            int regula = (number*10)-10;

            for(int i=regula; i<regula+9; i++) {
                System.out.println(list.get(regula));
            }
        }
    }     
}  

And in the line: System.out.println(list.get(regula));

I have an error. What should i do?

EDIT: List isn't empty for 100%. I just pasted fragment of code with an error inside of it hoping that someone would say how can i resolve a problem with "list-error". I want to add some info to the list and then choose certain "list-lines" and show those data.

Upvotes: 1

Views: 13146

Answers (3)

Paul Samsotha
Paul Samsotha

Reputation: 208974

List<String> list = new ArrayList<String>(); is only scoped within the inputData method. Declare it as a class member instead. That's why you're getting list can't be resolved at the System.out.pritnln(list.get(regla));. the list can't be accessed from that method as it's locally scoped in another method

public class Objects {

    List<String> list = new ArrayList<String>();

    void inputData() {

Also, you have no lista - lista.add(inputedData);. you only have a list

Probably want to change

lista.add(inputedData);

to

list.add(inputedData);

Upvotes: 0

Eric Abramov
Eric Abramov

Reputation: 511

At least put basic check in the for loop:

for(int i=regula; i < regula+9; i++){
    if (list.get(regula) != null)
        ...
    }

Upvotes: 1

Andrea
Andrea

Reputation: 2764

List is a local variable of inputData so you cannot access putside (I.e. from showData). Note also there's a missing } between the two methods

Upvotes: 1

Related Questions