Reputation: 47
I have 2 classes, dog and printing, the dog class is meant to send over a char[][] to printing so it can print to a printer. However, the dog class can't find the printing method in printing class.
//Printing class-
public class Printing implements Printable, ActionListener {
String str = "";
public String printString(char [][] grid ){
for(int i=0;i<9;i++){
for (int j=0;j<9;j++){
str += String.valueOf(grid[i][j]);
}
str += "\n";
}
return str;
}
}
I then require this str in another method as well.
When I type Printing.printString(grid);
it cannot be referenced from static context. When I change it to public static String(char [][] grid )
its method then can't find the str string variable.
Upvotes: 0
Views: 77
Reputation: 8657
You can't call Printing.printString(grid);
like this unless you make it a static.
Also if you made printString()
method as a static you need to declare str
as a static because you cant refer a non-static variables within a static methods.
So you code should look like this:
public class Printing implements Printable, ActionListener {
static String str = "";
public String printString(char [][] grid ){
for(int i=0;i<9;i++){
for (int j=0;j<9;j++){
str += String.valueOf(grid[i][j]);
}
str += "\n";
}
return str;
}
}
Read more about static variables and methods
Upvotes: 1
Reputation: 4923
static String str = "";
public static String printString(char [][] grid ){
for(int i=0;i<9;i++){
for (int j=0;j<9;j++){
str += String.valueOf(grid[i][j]);
}
str += "\n";
}
return str;
}
Now you can call the method using Printing.printString(grid);
The non-static instance variable can't be refer in static class and vice versa
Upvotes: 0
Reputation: 9162
this will help
public String printString(char [][] grid ){
String str = "";
for(int i=0;i<9;i++){
for (int j=0;j<9;j++){
str += String.valueOf(grid[i][j]);
}
str += "\n";
}
return str;
}
Upvotes: 0
Reputation: 151
The str
member must also be static. Just make sure that you reset it with each call to printString
.
class Printing
{
private static String str = "";
public static printString( char[][] grid )
{
str = "";
for(int i=0;i<9;i++)
{
for (int j=0;j<9;j++)
{
str += String.valueOf(grid[i][j]);
}
str += "\n";
}
return str;
}
}
Also, this isn't really part of the question, but I recommend the use of the StringBuffer
class in situations like this.
Upvotes: 0