-1

Hey I just started learning how to code. I am using netbeans and I want to transfer some data from a txt.file into an array in java. This might be a really simple fix but i just cant see whats wrong

This is the data in the txt.file:

58_hello_sad_happy
685_dhejdho_sahdfihsf_hasfi
544654_fhokdf_dasfjisod_fhdihds

This is the code I am using however smthg is wrong with the last line of code:

int points = 0;
String name = "";
String a = "";
String b = "";

public void ReadFiles() throws FileNotFoundException{
    try (Scanner input = new Scanner(new File("questions.txt"))) {
        String data;
        while(input.hasNextLine()){
            data = input.nextLine();
            String[] Questions = data.split("_");
            points = Integer.parseInt(Questions[0]);
            name= Questions[1];
            a = Questions[2];
            b = Questions[3];
        }   
        System.out.println(Arrays.toString(Questions));
    }
}

This is the error I am getting:

 error: cannot find symbol 
 System.out.println(Arrays.toString(Questions));

Thx soooo much guys.

  • 3
    You've declared `Questions` only in the scope of the `while` loop. Declare it outside of the loop. Also Java naming conventions is for variables to start with lower case – GBlodgett Aug 09 '18 at 21:47
  • I.e. change your code to: `String[] Questions; while(input.hasNextLine()){` and then later you can simply do: `Questions = data.split("_");` – GBlodgett Aug 09 '18 at 21:48
  • This might be helpful to read: https://www.geeksforgeeks.org/variable-scope-in-java/ – GBlodgett Aug 09 '18 at 21:52

1 Answers1

0

You can also use the below code if you just want to print the data:

    Files.readAllLines(Paths.get("questions.txt")).forEach(line -> {
        System.out.println(Arrays.toString(line.split("_")));
    });

Output is :

[58, hello, sad, happy]
[685, dhejdho, sahdfihsf, hasfi]
[544654, fhokdf, dasfjisod, fhdihds]

The correct version of your code should be like the below (you must access the variable Question in the declared scope by moving println into end of while loop) :

// definitions...

public void ReadFiles() throws FileNotFoundException{
    try (Scanner input = new Scanner(new File("questions.txt"))) {
        String data;
        while(input.hasNextLine()){
            data = input.nextLine();
            String[] Questions = data.split("_");
            points = Integer.parseInt(Questions[0]);
            name= Questions[1];
            a = Questions[2];
            b = Questions[3];
            System.out.println(Arrays.toString(Questions));
        }   
    }
}
Emre Savcı
  • 3,034
  • 2
  • 16
  • 25