A.Maine
A.Maine

Reputation: 117

Not being able to return an int from incrementation

My goal is currently to take a string looking like

                                                   "###### 
                                                    #    #
                                                    # @ ##"

@ is here my "character" and "#" is walls that should be avoided, I want my character to get out of the box and return the pathway, I realize my example is pretty bad but I hope you understand. The idea I have currently is to read in a text-file with that String, then creating an array as a 2-D grid and then work from there, the code I have currently is:

package soko;
import java.io.*;
import java.util.*;

public class Sokoban2 {
    static File file;
    Scanner input;
    static int b;
    static int c;
    static String[][] array;

    public Sokoban2() {
        //array = new String [9][9];
    }


    public int readFile() throws Exception{
        Scanner input = new Scanner(System.in);
        file = new File("C:/Users/joaki/Desktop/sokoban/readin.txt");
        input = new Scanner(file);
        while (input.hasNext()) {
            b = b + 1;
            String line = input.nextLine();
            System.out.println(line);
        }
        input.close();
        return b;
        //array = new String[5][5]; 
        }

    public void insertStuff() {
        //array[1][1]="2";


    }

    public void printStuff() {
    for (int r = 0; r<2;r++){
        String line2 = "";
        for (int d = 0; d <2;d++){
            line2+="["+array[d][r]+"]";
        }
        System.out.println(line2);
    }
    }

public static void main(String[] args) throws Exception{
    Sokoban g = new Sokoban();
    g.readFile();
    //g.insertStuff();
    //g.printStuff();
    //g.creatingGrid(c,b);
    //System.out.println(b);


}
}

I really want to print my b, at least check it's value, but my program wont return any value, it's not even returning a null or 0, I've tried to print it as well, no luck there either, ideas ?

Upvotes: 0

Views: 65

Answers (1)

vividpk21
vividpk21

Reputation: 384

You aren't returning the value to any variable, I just ran your code and it works fine, it counts the lines in the file.

    int b = g.readFile();
    System.out.println(b);

If you don't return the value to a variable you won't have access to the value of b in your main because it's out of scope, more about that here: https://www.cs.umd.edu/~clin/MoreJava/Objects/local.html

Edit: I actually just realized that you declared b in your class as static and I decided to run it as you have it above, I still get it printing out the amount of lines.

    g.readFile();
    System.out.println(b);

If you are going to have your function return a value and you don't plan on storing b then get rid of the static declaration in your class and just declare it in the function that returns b.

Upvotes: 1

Related Questions