Getting a nullpointer exception in variable initializer [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am relatively new to Java and ML but have been trying to learn, so forgive any noob mistakes. I have been following an article about ML in python have been trying to kind of translate it to Java to train the language and learn about the subject in the process, I have been getting a NullPointerException at the line of the variable loss and when I try to initialize the method in the main class, I can`t seem to find the problem.
I have tried running the method in a non static way and just rewriting everything, but it doesn`t seem to work.
public static double calcLoss() {
for (int i = 0; i < y_true.length; i++) {
double a = (1 / y_true.length) * Math.pow(y_true[i] - y_pred[i], 2);
loss = a;
}
return loss;
}
I know it says not to do it but here is a pastr with the full code, maybe this helps. https://pastr.io/view/bSacVk
This is the error
>Exception in thread "main" java.lang.NullPointerException
>at Net.Neuron.calcLoss(Neuron.java:40)
>at Net.Main.main(Main.java:28)

I have been getting a NullPointerException at the line of the variable
loss and when I try to initialize the method in the main class, I
can`t seem to find the problem.
That's because one of y_true or y_pred is likely null. You can easily handle this case by adding a if statement like this,
public static double calcLoss() {
if (null != y_true && null != y_pred && y_pred.length == y_true.length) {
for (int i = 0; i < y_true.length; i++) {
double a = (1d / y_true.length) * Math.pow(y_true[i] - y_pred[i], 2);
// This is just re-assigning loss. Are you sure this is what you intended here?
loss = a;
}
return loss;
}
// y_true is NULL.
return -1;
}
Also, I'm not sure what is the original intent here but, you are just reassigning loss in every iteration of the loop.

Related

while I try to run basic Java code there was some variable scope error why it happens? [duplicate]

This question already has answers here:
Java: Error: variable might not have been initialized
(2 answers)
Closed 6 months ago.
class HelloWorld {
public static void main(String[] args) {
int sum;
for (int i = 0; i < 10; i++) {
if (i == 9) {
sum = 10;
}
}
System.out.println(sum);
}
}
why this code gives this error?
HelloWorld.java:9: error: variable sum might not have been initialized
System.out.println(sum);
We can look at the code and intuitively reason that sum will always have a value by the time it's used, because the loop will always execute and one of the iterations will satisfy the if condition.
But the compiler doesn't intuitively reason any of that. It sees a loop and a conditional block and it can't guarantee that sum will have a value by the time it's used. To the compiler, it's possible that loops may iterate 0 times or that conditions may never be true.
Basically, we can "test the code" in our heads and predict its outcome. But the compiler doesn't test the code, no matter how simple the code may be.
You can correct the problem by simply initializing the value:
int sum = 0;

Number.isInteger method cannot be found [duplicate]

This question already has answers here:
How to test if a double is an integer
(18 answers)
Closed 1 year ago.
I am a Java newbie and I am facing this error here. Any help would be appreciated. Thank you!
The error is:
symbol: method isInteger(double)
location: class number
Program:
int num = Integer.parseInt(num1.getText());
double square = Math.sqrt(num);
if (Number.isInteger(square))
outputlbl.setText("Number is a perfect square");
else
outputlbl.setText("Number is not a perfect square");
I think you are confusing the Java method with Javascript Number.isInteger().
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
Unfortunately, we don't have this in java directly.
However, you can use the below code to check if double is an integer or not.
double d = 5;
if( (d % 1) == 0 ) {
System.out.println("Yes");
}
else{
System.out.println("No");
}
PS: This is one of the ways to check if double is an integer or not . If you dig more in java, you will certainly find more ways to do the same.
The Java class Number doesnt have this function. (it exists in javascript though)
Alternatively you can write an easy helper function to solve this problem:
private boolean isInteger(double num)
{
if (num==(long)num)
return true;
return false;
}
The code should be pretty self explanatory.

having trouble creating a rounding program java using command lines [duplicate]

This question already has answers here:
Variable might not have been initialized error
(12 answers)
Closed 6 years ago.
I'm fairly new to coding and I've been learning by creating simple programs.
I'm trying to create a program called roundGrade to round a grade to one decimal place by calling onto the command line.
The error stated:
Error: variable roundGrade might not have been initialized
Here's the code I've written so far:
public static String roundGrade(double grade){
String roundGrade;
double R = Double.parseDouble(roundGrade);
R = Math.round(grade*10)/10;
roundGrade = Double.toString(R);
return roundGrade;
}
You are attempting to parse roundGrade before you set it to anything (and for no apparent purpose). This
double R = Double.parseDouble(roundGrade);
R = Math.round(grade*10)/10;
should be something like
double R = Math.round(grade*10)/10;
And your entire method could be
return String.format("%.1f", grade);

NullPointerException in Java my java program [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm working on a program using eclipse that generates objects for runners in a 100 m race.
each runner has a lane, name and three separate times for completing the race.
However, when I try to generate the times for each object, I get java.lang.NullpointerException.
Here is the method for generating the times.
public double[] getTimes() {
for (int i = 0; i <= (times.length - 1); i++) {
rolled = 1.0 + roll.nextDouble() * 100.0;
// set rolled to a new random number between 1 and 100
times[i] = rolled;
// set index i of the array times to be the nearest
// double to roll's value.
}
return times;
}
and then the code in which the method is called.
public void testGetTimes() {
double[] times = performance.getTimes();
assertEquals(2, times.length);
assertEquals(9.2, times[0], 0.01);
assertEquals(9.4, times[1], 0.01);
}
I'd try to fix it through debugger, but every time i try to step-into the for loop, i get InvocationTargetException,(Throwable line: not available
initialization of times, roll and rolled:
public class Performance {
private int lane;
private String name;
double[] times = new double[3];
int rolling;
Random roll = new Random();
double rolled;
double average;
double best;
and of performance:
public class PerformanceTest {
Performance performance;
#Before
public void setup() {
performance = new Performance(1, "", new double[]{9.2, 9.4});
}
It looks like one of your objects is uninitialized. On the other hand, initializing it to null can cause the same problem. As of Java 8, I would suggest using an Optional to contain any values that you are not immediately certain of, or are not immediately aware of, and put their processing in an Optional.ifPresent(Consumable) statement. It minimizes the possibility of a NullPointerException, and invites functional programming methods, which will seriously slim down the amount of time it takes to get the job done.
As far as your assertion error goes, I'm sure you already know that this is only caused by an assert statement. Looks like times[0] is substantially larger than you were expecting. It appears, from what we can see, that you're setting it to 1.0 + random{0.0...1.0} * 100.0; I don't know what the precondition that leads you to expect 9.4 is, but this could easily hit the forties.

Checking Left/Right in an int array for Tetris, Android/Java

I'm trying to make a tetris game for android to help learn game programming for android. My goLeft/Rights break right when the button is pressed, the code for going left is in a class separate of the fields int array, and the list parts array. The fields array is accessed by a referenced variable (TetrisWorld tetrisworld;). While part list array is public so accessed through a variable(part) code for which is in the goLeft() code. It breaks at: if(tetrisworld.fields[x][part.y] != 0) Code for left:
public void goLeft() {
int x = 0;
for(int i = 0; i < 4; i++) {
TetrisParts part = parts.get(i);
x = part.x - 1;
if(tetrisworld.fields[x][part.y] != 0) {
noleft = true;
break;
}
}
if(noleft == false) {
for(int i = 0; i < 4; i++) {
TetrisParts part = parts.get(i);
part.x--;
}
}
}
The code for the fields int array:
int fields[][] = new int[WORLD_WIDTH][WORLD_HEIGHT];
WORLD_WIDTH and WORLD_HEIGHT are both static final ints, width being 9 and height being 19
I've tried putting if(tetrisworld.fields[0][0] == 0) and it still crashes so I don't think it has to do with the variables. Also It doesn't go out of bound even if I haven't added the code to check for that yet because I have the teroid spawning around x = 5 and since I can't go left/right once there's not a chance of that happening
I've tried moving the goLeft/Right methods to the gamescreen class which has a "world = TetrisWorld();" and it still bugs out at the same spot
UPDATE:
Ok just adding:
tetrisworld != null
to the first if statement fixed it, my question now is, why did it fix it? Why can't I move without this check? It clearly isn't null cause as far as I know; it's fully responsive now.
But an easier way to have solved this which is SOOOO easy is changing fields to static... then access it lika so: TetrisWorld.fields so my updated code is:
public void goLeft()
{
noleft = false;
for (int i = 0; i < 4; i++)
{
part = parts.get(i);
if (part.x - 1 < 0 || TetrisWorld.fields[part.x - 1][part.y] != 0)
{
noleft = true;
break;
}
}
if (noleft == false)
{
for (int i = 0; i < 4; i++)
{
part = parts.get(i);
part.x--;
}
}
}
Looks like you are hitting IndexOutOfBoundsException.
When you are doing x = part.x - 1;, your x variable can become lesser tan zero, thus your code will act like if(tetrisworld.fields[-1][part.y] != 0
It looks like you're getting a java.lang.NullPointerException when trying to access the array in tetrisworld. In the line you mention there are several ways that this could occur:
if(tetrisworld.fields[x][part.y] != 0) {
tetrisworld could be null.
The fields member of tetrisworld could be null.
The second array that you're looking up by using tetrisworld.fields[x].
The value of part could be null.
Having a quick look through your source code it looks to me like you never initialise tetrisworld, either at declaration using:
TetrisWorld tetrisworld = new TetrisWorld();
Or at some other point which is certain to have happened before your goLeft() method is called.
Ok I believe I found the answer, referencing: http://en.wikipedia.org/wiki/Null_Object_pattern
Apparently java will throw an NPE if you don't check for it first if you have a null reference? Is there any way to initialize it without doing a TetrisWorld tetrisworld = new TetrisWorld(); because it's already created in a different class so i get a thousand errors, an actual stack overflow! lul... Still not 100% positive. Please comment to verify and possibly suggest a better way to go about this.

Categories