When compiled this static method comes up with the error that the int array variable, coord, cannot be found. I declared it within the method and it is of the type int[] and I can't figure out why it won't work. I have a feeling that it has to do with the method being static, but changing it to static was the only way I found to make that method work in the first place.
I feel like this is probably really simple for anybody but me especially when all I could find on this subject were much more complicated coding issues.
In case this helps.. this method is supposed to return the (x,y) coordinates for a move location. Sorry for probably not inputting the code correctly. First time doing this. Thanks in advance for any help
CODE:
public static int[] getMove(String player)
{
boolean done = false;
while(!done)
{
Scanner in = new Scanner(System.in);
System.out.println("Input row for " + player);
int x = in.nextInt() - 1;
System.out.println("Input column for " + player);
int y = in.nextInt() - 1;
int[] coord = {x,y};
if(getLoc(coord[0], coord[1]).equals("x") || getLoc(coord[0], coord[1]).equals("o") || coord[0] < 0 || coord[0] > ROWS || coord[1] < 0 || coord[1] > COLUMNS)
{
System.out.println("Invalid coordinates... please retry");
}
else
{
done = true;
}
}
return coord;
}
What you are missing is the scope of the variable. A variable declared in parent block is accessible in child blocks, but not the other way around.
public void someMethod()
{
int x=1;
while(x<10)
{
x++; //x is accessible here, as it is defined in parent block.
int j = 0; //This variable is local to while loop and will cause error if used inside method
j++;
}
System.out.println(j);// The outer block does not know about the variable j!!
}
Now in your case,
Notice where you have defined coors, and in what all places you are using it.
Try to figure where should you define coors variable.
That is because the array coord is local to the while loop. And therefore its not visible outside its scope. Move the declaration of coord outside the while and it should work.
int[] coord = new int[2];
while(!done){
...
...
coord[0] = x;
coord[1] = y;
...
}
Related
Consider the following method:
void a ()
{
int x;
boolean b = false;
if (Math.random() < 0.5)
{
x = 0;
b = true;
}
if (b)
x++;
}
On x++ I get the "Local variable may not have been initialized" error. Clearly x will never be used uninitialized. Is there any way to suppress the warning except by initializing x? Thanks.
No, there is no way Java can examine all possible code paths for a program to determine if a variable has been initialized or not, so it takes the safe route and warns you.
So no, you will have to initialize your variable to get rid of this.
There is one :
void a () {
if (Math.random() < 0.5) {
int x = 1;
}
}
The compiler isn't responsible for devising and testing the algorithm. You are.
But maybe you should propose a more practical use case. Your example doesn't really show what's your goal.
Why don't you simply use
void a ()
{
int x;
boolean b = false;
if (Math.random() < 0.5)
{
x = 0;
b = true;
x++;
}
if (b) {
//do something else which does not use x
}
}
In the code why do you want to use x outside the first if block, all the logic involving x can be implemented in the first if block only, i don't see a case where you would need to use the other if block to use x.
EDIT: or You can also use:
void a ()
{
int x;
boolean b = (Math.random() < 0.5);
if (b) {
x=1
//do something
}
}
You can and should be defining the value of x unconditionally if it will be used later in your code.
There are a few ways to do this:
On initialization
int x = 0;
Because this is outside the conditional (if), Java won't complain.
Add else clause to conditional
if (Math.random() < 0.5)
{
x = 0;
b = true;
} else
{
x = 1;
}
Because there is an else to this if, and both code paths initialize x, Java will also be happy with this.
Move your usage of the variable into the conditional block
Clearly the question has a minimally-reproducible example, not a full one, but if you only ever want to use the variable conditionally, then it belongs in the conditional block.
if (Math.random() < 0.5)
{
x = 0;
x++;
}
If you don't aren't conditionally using the variable, then you need to provide an integer value to use in case Math.random() >= 0.5, using one of the solutions above.
To start things off, I am making a game. You fight on a 3x3 Grid (using a 2 Dimensional-Array), and if the "Lane#" (Lane# = Row + Col) ahead of you is blank then you get a -15% Damage Reduction, and this stacks for every blank lane.
This means if you are on [0][0] then you are in Lane# 0, and therefore, cannot possibly have anyone ahead of you, and you will always take 100% of Damage (this is of course without defense and yadda yadda else that modifies)
And if you are on [2][2] then you are in Lane# 4, and if every lane ahead of you has atleast one space in it taken, then you will take 15*4 = 60, 100-60 = 40% of actual damage.
Now that that is out of the way. I am having difficulty returning 0... I keep getting an Error that says that you cannot return a Void value...
'cannot return a value from method whose result type is void'
public Blanks(int l) { //l = Lane
int x = 0; //The Return
for (int i = 0; i < 6; i++) //The loop
if (l=0){ //Here I keep getting an error saying 'incompatible types'
x = 0;
return x; //Here is the 'cannot return a void value' error
break;
}
if (l>=1){
x++;
}
if (l>=2){
x++;
}
if (l>=3){
x++;
}
if (l>=4){
x++;
}
return x; //for some odd reason, this is also a void value
}
}
I still have yet to add the Checking the Array / Grid part as I am stumped about that one as well.. but another problem, another question.. the actual array itself..
you should modify the method header to public int Blanks(int l) {
and you should remove break; keyword because you return method value before it and will be unreached statement.
In order to return an integer value you have to mention a return type in the method. Also, in the first if statement you have used assignment operator instead of comparing.
Also why you have used break after return. I think you have to do first break and then return in the end.
One more thing to add. Your for loop should contain braces. Only the first if statement will get executed according to your code.
public int Blanks(int l) { //l = Lane
int x = 0; //The Return
for (int i = 0; i < 6; i++) //The loop
if (l==0){ //Here I keep getting an error saying 'incompatible types'
x = 0;
break;
}
if (l>=1){
x++;
}
if (l>=2){
x++;
}
if (l>=3){
x++;
}
if (l>=4){
x++;
}
return x; //for some odd reason, this is also a void value
}
}
I haven't stepped into your logic. Comment if you face any problem after this.
I don't understand why you are using the for loop here, but this is a way to do it:
public int Blanks(int l) {
int x = 0;
for (int i = 0; i < 6; i++)
if (l==0){
x = 0;
}else {
x++;
}
return x;
}
But in case that l==0 your method will return 5;
If you want to return 0 or 1 then you need to remove the for loop
public int Blanks(int l) {
if (l==0) return 0;
else return 1;
}
And the method with true-false:
public boolean Blanks(int l) {
if (l==0) return false;
else return true;
}
I have tried writing the algorithm by referring this.
But i am getting Error of StackOverFlow.
Help me out to find what is wrong in the program? Is it the recursion part?
public void beginSolving(int board[][],int x,int y){
int i = 1;
if(unassignedCell(board,x,y)){
board[x][y] = i;
if(isValidCell(board,y,x,i)){
board[x][y] = i;
}
if(!isValidCell(board,y,x,i)){
board[x][y] = 0;
i++;
}
} else {
while(x<9){
beginSolving(board,x++,y);
if(x==9){
x = 1;
beginSolving(board,x,y++);
if(y==9){
}
}
}
}
}
Look at the recursive calls: beginSolving(board,x++,y). The x and y parameters are the same as in the original call (remember that the value of x++ is the value before it is incremented). Thus it is likely that you enter a never ending recursion.
The while(x < 9) will never terminate since whenever x reaches 9 it is reset to 1.
The algorithm never tries to set a number other than 1 into the board.
There may be other problems with the code as well, I did not check it in detail.
I am trying to make a snake-type game in Java.
To do so, I am using lists to keep hold every of the snake's body parts with
ArrayList<SnakeBodyPart> snakeBodyParts = new ArrayList<SnakeBodyPart>();.
I declare and initiate a variable, SnakeBodyPart SnakeBodyPart = null;.
I then add a body part to the snake with snakeBodyParts.add(SnakeBodyPart);.
(Not the most efficient way, I guess, but it'll have to do.)
But for some reason, whenever I run the script, I get
Exception in thread "main" java.lang.NullPointerException,
and that the error is
at game.Snake.<init>(Snake.java:60)
in the Java console.
I want to know what the problem is. Here is the code for the SnakeBodyPart.
class SnakeBodyPart{
int x,y,direction;
void move(){
if(direction == 0){
y -= 50;
}
if(direction == 1){
x += 50;
}
if(direction == 2){
y += 50;
}
if(direction == 3){
x -= 50;
}
}
}
Thanks in advance!
EDIT:
Line 60 is snakeBodyParts.get(0).direction = 0;.
You have done this:
SnakeBodyPart snakeBodyPart = null;
Create the object
SnakeBodyPart snakeBodyPart = new SnakeBodyPart();
Since snakeBodyPart is null, you are getting NullPointerException in Line 60. You are calling get() method on null as snakeBodyParts.get(0).direction = 0;
I'm new to Java and I'm having a bit of trouble understanding the concept of the declaration and the initialization of variables.
For example, when I do:
public class Foo {
public static void main (String[] args) {
int x, y;
for (x = 0 ; x < 10 ; x++) {
y = x + 1;
}
System.out.println(x);
System.out.println(y);
}
}
It does not compile and says that "variable y might not have been initialized."
However, it does not have any trouble if I tell it to just print out the x value after the loop. Of course it would work if I simply declared it in the beginning (saying int y = 0; or something like that), but I wanted to know why x is printed but not y.
Thanks in advance!
Edit:
I understand that the compiler doesn't actually check inside the loop to see if the variable would be initialized or not so it just says it might not have been initialized, but then why does the following code work? Does the compiler check the if loop but not the for loop?
public class Foo {
public static void main (String[] args) {
int x = 0, y;
if (x == 0) {
y = 1;
}
else {
y = 2;
}
System.out.println(y);
}
}
Edit 2:
It looks like it gives me the same error if I actually give another condition for the else part so that it would be:
if (x == 0) {
y = 1;
}
else if (x == 1) {
y = 2;
}
So I guess the other example worked since y was initialized in both the if and the else part, which means the y would always be initialized no matter what the condition given is. Now I really get it. Thank you!!
local variables don't have a default value and you need to initialize them. You are certainly setting the value of x (x=0), but the compiler doesn't check if the loop body will be actually entered. So give y a value of 0.
This is wrong:
public class Foo {
public static void main (String[] args) {
int = x, y; // Wrong
for (x = 0 ; x < 10 ; x++) {
y = x + 1;
}
System.out.println(x);
System.out.println(y);
}
}
This is correct:
public class Foo {
public static void main (String[] args) {
int x, y; // Declaration only: x and y are uninitialized
This is also correct:
public class Foo {
public static void main (String[] args) {
int x = 1, y = 10; // Declaration + initialization
'Hope that helps...
If you look in your code; you have initialized x to 0 in for loop and then incrementing it with x++. But you are initializing Y inside loop which may or may not execute at runtime (nothing to do with compile time). In Java, you have to initialize local variable before using it and if you are not doing so compiler will prompt the error. And that is why x is printed and not Y
It cannot be determined until run-time whether the for loop will be run even once. Therefore that initialization doesn't count (i.e., the compiler cannot depend on it, so it errors).
It cannot be determined until run-time which of the two -- the if or the else clause -- will fire. However, at compile-time we know that one OR the other will fire, so if you initialize in both, the compilation error goes away.
x gets initialized in the for loop (first argument)
Consider what could happen if your loop was
for (x = 0 ; x < someOtherVariable ; x++) {
and the value of someOtherVariable happened to be zero. The loop wouldn't run at all, so y would never be initialized.
Of course, the loop you wrote will always run ten times since the lower and upper bound are both hard-coded, but the compiler (apparently) doesn't analyze the code enough to prove that. It sees a variable that's only initialized within a loop, and following the general rule that a loop might not run at all, it complains that the variable might not be initialized.
BTW, int = x, y; isn't valid Java syntax: the equals sign doesn't belong there.
It depends on two things:
executes no matter what (here "x")
executes based on some constraint (here "y")
The compiler repels ambiguity in any case so it throws error on witnessing a variable initialization in a block which is conditionally executed.