I am trying to get a better understanding of private and public methods. I am trying to make a private method called GRID_SIZE and let that equal the length(m) of my grid, however, I am getting a message saying that it cannot be resolved into a variable. My understanding is that if a method is private only the class can access it and if a method is public any class can enter. So I am confused as to why I can't take a variable from the public method to a private method.
public class trial1 {
private static final int GRID_SIZE = m;
public static void main(String[] args) {
int m = 8;
char[][] grid = new char[m][m];
for (int i=0; i<grid.length; i++) {
for(int j = 0; j<grid[i].length; j++) {
grid[i][j] = '*';
StdOut.print(grid[i][j]);
}
StdOut.println();
}
}
}
You're creating a static field, not a method. The visibility is not relevant to the question.
Static (class) variables simply cannot be set before the class is initialized; there is no m until the main method is executed (after the class is instantiated by the JVM). Plus, you've made the field final, so it cannot be modified within the main method, anyway.
Perhaps you want this?
public class Trial1 {
private static final int GRID_SIZE = 8;
public static void main(String[] args) {
char[][] grid = new char[GRID_SIZE][GRID_SIZE];
Your problem here is around scope.
Variables defined within a method are only visible within that method. So in your code the variable m is only accessible by code inside the main class.
GRID_SIZE is a private static field (not a method) and that means it is accessible by all code within the class.
If you want GRID_SIZE to be assigned a value defined in method scope (e.g. m) then you need to remove the final from GRID_SIZE and set it from within the main method.
Something like:
public class Trial1 {
private static int GRID_SIZE ;
public static void main(String[] args) {
int m = 8;
GRID_SIZE = m;
char[][] grid = new char[m][m];
for (int i=0; i<grid.length; i++) {
for(int j = 0; j<grid[i].length; j++) {
grid[i][j] = '*';
StdOut.print(grid[i][j]);
}
StdOut.println();
}
}
}
Please note this is just an example of how to change GRID_SIZE. If you just want GRID_SIZE to always be a particular value then as the previous answer states you could just set it directly to 8.
Related
Apologies for posting a bit of a foolish question, but I cant seem to understand why my method startEndCoords does not seem to run properly through my main method here:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class MazeSolver {
// The name of the file describing the maze
static String mazefile;
// set global variables
static int arrayHeight;
static int arrayWidth;
static int startRow;
static int startColumn;
static int endRow;
static int endColumn;
static int cellsize;
static int borderwidth;
static int sleeptime;
static char [][] maze;
public static void main(String[] args) throws FileNotFoundException {
if (handleArguments(args)) {
maze = readMazeFile(args[0]);
startEndCoords(maze);
if (solveMaze(startRow, startColumn))
System.out.println("Solved!");
else
System.out.println("Maze has no solution.");
}
}
// get starting & ending points
static boolean startEndCoords(char[][] mazeAsArray){
for (int r = 0; r < MazeSolver.arrayHeight; r++) {
for (int c = 0; c < MazeSolver.arrayWidth; c++) {
if (mazeAsArray[r][c] == 'S') {
MazeSolver.startRow = r;
System.out.println(startRow);
MazeSolver.startColumn = c;
System.out.println(startColumn);
}
if (mazeAsArray[r][c] == 'E') {
MazeSolver.endRow = r;
System.out.println(endRow);
MazeSolver.endColumn = c;
System.out.println(endColumn);
return true;
}
}
}
return false;
}
The print statements within the method will not execute, not sure what im missing.
Thanks for your help.
full code
It appears that your readMazeFile method is intended to set some of the global variables you declare, but it actually doesn't. It instead declares its own local variables that happen to have the same names, and sets those. This leaves MazeSolver.arrayHeight at its default value of 0, so of course the for loop instantly bails before even running once.
Remove the int from the lines in readMazeFile that set arrayHeight and arrayWidth. This will make it use and set the existing static variables instead of creating new local ones.
I just started with java and I create a class Range() inside my superclass with a method inside makeRange but when I tried to access to that method throws an error. Whats wrong here?
Here is my code...
public class iAmRichard {
class Range{
int[] makeRange(int upper, int lower){
int[] ary = new int[(upper - lower)+1];
for(int i = 0; i > ary.length; i++ ){
ary[i] = lower++;
}
return ary;
}
}
public static void main(String[] args) {
int foo[];
Range fui = new Range();
foo = Range.(here do not apear makeRange method)
You're creating an inner class here called Range. I don't believe that's what you intended to do, but I'll answer it as stated.
You're referring to this class in a static context, and the inner class can't be referenced with a static context. To address that, you need to make the change to Range: make it static.
public class iAmRichard {
static class Range {
}
}
Further, you're already getting an instance of Range, so all you need to do is use it.
foo = fui.makeRange(1, 10);
If you elected to only create a class called Range, you wouldn't have to deal with any inner classes at all, which I think would be the cleaner approach here.
public class Range {
int[] makeRange(int upper, int lower) {
int[] ary = new int[(upper - lower) + 1];
for (int i = 0; i > ary.length; i++) {
ary[i] = lower++;
}
return ary;
}
public static void main(String[] args) {
int foo[];
Range fui = new Range();
foo = fui.makeRange(1, 10);
}
}
To access a method without creating an instance you have to declare it static. In your case you have also to declare the class Range as static.
Or you can just use the instance you already have with a few changes:
iAmRichard richard=new iAmRichard();
Range fui=richard.new Range();
foo = fui.makeRange(...);
Note tha you need an instance of iAmRichard to create a Range.
Since the call is made from a static block in a static way(No instance is used for calling makeRange method) we need to have the called method to be either static or we need the object of the class to call instance methods.
statically you can use this example to access your method. Here is a link for more information on static methods.
public class IAmRichard {
public static void main(String[] args) {
int foo[];
foo = Range.makeRange(10,1);
}
static class Range{
static int[] makeRange(int upper, int lower){
int[] ary = new int[(upper - lower)+1];
for(int i = 0; i > ary.length; i++ ){
ary[i] = lower++;
}
return ary;
}
}
}
I'm trying to get a radix sort going with an array of queues to avoid long rambling switch statements but I'm having some trouble getting the array properly initialized. The constructor and an example of an implementation are given below.
I'm just getting a cannot find symbol error when I try to compile though.
public static radixj(){
IntQueue[] buckets = new IntQueue[10];
for (int i = 0; i < 10; i++)
buckets[i] = new IntQueue();
}
public static void place(int temp, int marker)
{
int pos = temp % marker;
buckets[pos].put(temp);
}
I'm pretty sure it is a really simple mistake that I'm making but I can't find it. Any help would be greatly appreciated.
In your code
IntQueue[] buckets = new IntQueue[10];
is a local variable to the function
public static radixj()
which must have a return type
public static void radixj()
So then you can't use it in another function
buckets[pos].put(temp);
You should declare a static class variable
class Foo {
static IntQueue[] buckets = new IntQueue[10];
...
and access it using: Foo.buckets
class Foo {
public static IntQueue[] buckets = new IntQueue[10];
public static void radixj() {
for (int i = 0; i < 10; i++) {
Foo.buckets[i] = new IntQueue();
}
}
public static void place(int temp, int marker) {
int pos = temp % marker;
Foo.buckets[pos].put(temp);
}
}
the return type in radixj() is missing and buckets cannot be resolved to a variable
I've got two compile errors in one of my classes and I don't understand why they're there.
The top error is saying there needs to be another semi-colon and the bottom one says it needs another closing brace.
The bottom error disappears if i put in another curly brace but the top one doesn't. Any ideas?
(This is probably a case of me being blind/stupid so i apologise in advance :)
package com.pathfinding;
import java.util.ArrayList;
public class EdgeNodeFactory
{
static boolean[][] edgeMatrix = new boolean[100][100];
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
edgeMatrix[i][j] = false;
}
}
static ArrayList<Node> nodes = new ArrayList<Node>();
static ArrayList<Edge> edges = new ArrayList<Edge>();
static int edgeCount = 0;
static int nodeCount = -1;
}
You've tried to put code (the for loop) directly in your class - it's not in a constructor, a method, or a static/instance initializer. That's not valid. When do you want that code to be executed?
I suspect your code should really look like this:
public class EdgeNodeFactory
{
private boolean[][] edgeMatrix = new boolean[100][100];
private int edgeCount = 0;
private int nodeCount = -1;
private List<Node> nodes = new ArrayList<Node>();
private List<Node> edges = new ArrayList<Edge>();
public EdgeNodeFactory()
{
// You *could* put your for loop here... but the array
// elements will all be false anyway, as that's the default...
// If you don't need any code in this constructor, and you
// don't declare any other constructors, you can remove it
// entirely - the compiler will create it by default.
}
// Other methods here
}
Note how I've made all the fields private and non-static... you should almost certainly be creating an instance of EdgeNodeFactory rather than using static fields, and you should almost always make fields private.
Has been a while since I did any Java, but I believe that for loop should be inside a method or function of some description, rather than the class declaration.
I would imagine you mean that to be in a constructor.
I think what the for loops are meant to do is initialization of static array field. In this case you should put the code in a static initializer like this:
package com.pathfinding;
import java.util.ArrayList;
public class EdgeNodeFactory
{
static boolean[][] edgeMatrix = new boolean[100][100];
static {
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
edgeMatrix[i][j] = false;
}
}
}
static ArrayList<Node> nodes = new ArrayList<Node>();
static ArrayList<Edge> edges = new ArrayList<Edge>();
static int edgeCount = 0;
static int nodeCount = -1;
}
The code inside static { ... } at the class level is executed the first time the class is loaded (only once). This means it will be executed before any instances of the class are created and before any other code can access the class.
It remains debatable whether the fields should be static, but if you're sure they should, this is how you should initialize them.
All,
I am trying to code a Connect4 game. For this, I have created a P4Game class and a P4Board class which represents the i X j dimensions of the Connect4 board.
In P4Game, I have the following:
public class P4Game{
//INSTANCE VARIABLES
private int nbLines;
private int nbColumns;
private P4Board [][] position;
//CONSTRUCTOR
public P4Game(int nbLines, int nbColumns){
this.nbColumns = nbColumns;
this.nbLines = nbLines;
P4Board [][] position = new P4Board [nbLines][nbColumns]; //Creates the table to receive the instances of the P4Board object.*/
for (int i=0; i<nbLines; i++){
for (int j=0; j<nbColumns; j++){
this.position[i][j] = new P4Board(i,j); //Meant to create each object at (line=i, column=j)
}
}
}
This causes a NullPointerException in the nested loops where I mention this.position[i][j]. I reference those objects in other methods of this class so I need them to be instance variables. I suppose the exception is due to the fact that I have not listed the table element position[i][j] as an instance variable at the beginning of the class.
my question to people here is (1) is my assumption correct, and if so (2) what would be the syntax to declare instance variables of this form?
Thank you all for your help with what I realize is a very basic question. Hopefully it will also benefit other newbies.
Cheers,
JDelage
See added comment inlined... You code is fine except for one little detail, where you're creating a new position variable where you actually mean to use the instance variable.
public class P4Game{
//INSTANCE VARIABLES
private int nbLines;
private int nbColumns;
private P4Board [][] position;
//CONSTRUCTOR
public P4Jeu(int nbLines, int nbColumns){
this.nbColumns = nbColumns;
this.nbLines = nbLines;
// You're creating a LOCAL variable called position here if you don't comment what's commented:.
/*P4Board [][] */position = new P4Board [nbLines][nbColumns]; //Creates the table to receive the instances of the P4Board object.*/
for (int i=0; i<nbLines; i++){
for (int j=0; j<nbColumns; j++){
this.position[i][j] = new P4Board(i,j); //Meant to create each object at (line=i, column=j)
}
}
}
}
Your assumption is incorrect.
In the constructor, you're making a local variable with the same name as the field. (By writing P4Board [][] position = ...) This creates a local variable and does not affect the field, which remains uninitialized. You need to remove the P4Board [][] to change it from a variable declaration to an assignment of the existing field. (Just like you write this.nbLines = ... to assign the field)
You're redefining P4Board [][] position in the constructor and then calling this.position which is not initialized (i.e. null).
Look out carefully! You are hiding the instance variable > P4Board [][] position = new P4Board [nbLines][nbColumns];
As others have said you are hiding the instance variable with a local variable. You should really check out checsktyle as it has checks to tell you if you have made such a mistake. Two other tools are PMD and FindBugs.
Your assumption is incorrect. Try looking a few lines higher for the bug in your homework.
This runs for me. I substituted into for P4Board, since you didn't supply it:
public class P4Game
{
private int nbLines;
private int nbColumns;
private int [][] position;
public static void main(String[] args)
{
P4Game game = new P4Game(3, 3);
System.out.println(game);
}
public P4Game(int nbLines, int nbColumns)
{
this.nbColumns = nbColumns;
this.nbLines = nbLines;
this.position = new int[this.nbLines][this.nbColumns];
for (int i=0; i < this.nbLines; i++)
{
for (int j=0; j < this.nbColumns; j++)
{
this.position[i][j] = i+j;
}
}
}
public String toString()
{
StringBuilder builder = new StringBuilder(1024);
builder.append('[');
for (int i = 0; i < this.nbLines; ++i)
{
builder.append('{');
for (int j = 0; j < this.nbColumns; ++j)
{
builder.append(this.position[i][j]).append(',');
}
builder.append('}');
}
builder.append(']');
return builder.toString();
}
}