Error in Eclipse Luna 'Variable is not initialized' when declared outside of For loop and initialized within it - java

When using Eclipse Luna I run into this issue: When I declare a variable outside of the for loop (or another structure), then initialize it within the For loop, upon closing the for loop the value assigned to the variable within the for loop is not carried over.
Perhaps this is how it's supposed to be, but when using Eclipse Juno I don't have this problem.
int sebastian;
for(int i=0;i<8;i++)
{
sebastian = 5*i;
System.out.println(sebastian);
}

I'm not sure what's wrong there, but it SHOULD be carried over. It looks like it carries over, and when I run it, it carries over.
I ran
public static void main(String[] args) {
int sebastian = 0;
for (int i = 0; i < 8; i++) {
sebastian = 5 * i;
System.out.println(sebastian);
}
// this should print the last value a second time
System.out.println(sebastian);
}
and my output was
0
5
10
15
20
25
30
35
35 // this is the carry over that shows up

See rules for 'Definite Assignment' in the Java Language Spec. You can't refer to a local variable before it has a value assigned:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-16.html

Local variables do not have default values. When you write int sebastian; in a method, the variable sebastien does not the value 0, rather it is unassigned. You cannot use the variable until it is "definitely assigned". The rules for definite assignment are complicated. It seems clear that the variable will have been given a value in the loop (because the loop repeats 8 times), but that does not meet the rules for definite assignment.
int sebastian;
for(int i=0;i<8;i++)
{
sebastian = 5*i;
System.out.println(sebastian); // sebastien is definitely assigned here. It was assigned the line before!
}
System.out.println(sebastian); // sebastien is not definitely assigned here.
The easiest way round this to just give the variable a "dummy" value when you declare it:
int sebastien = -1;

Related

Variable in for loop is giving a message that "The value of the local variable i is not used"

I wrote a for loop that is supposed to determine if there is user input. If there is, it sets the 6 elements of int[] valueArr to the input, a vararg int[] statValue. If there is no input, it sets all elements equal to -1.
if (statValue.length == 6) {
for (int i = 0; i < 6; i++) {
valueArr[i] = statValue[i];
}
} else {
for (int i : valueArr) {
i = -1;
}
}
I am using Visual Studio Code, and it is giving me a message in for (int i : valueArr) :
"The value of the local variable i is not used."
That particular for loop syntax is still new to me, so I may be very well blind, but it was working in another file:
for(int i : rollResults) {
sum = sum + i;
}
I feel that I should also mention that the for loop giving me trouble is in a private void method. I'm still fairly new and just recently started using private methods. I noticed the method would give the same message when not used elsewhere, but I do not see why it would appear here.
I tried closing and reopening Visual Studio Code, deleting and retyping the code, and other forms of that. In my short experience, I've had times where I received errors and messages that should not be there and fixed them with what I mentioned, but none of that worked here.
for (int i : valueArr) {
.... CODE HERE ...
}
This sets up a loop which will run CODE HERE a certain number of times. Inside this loop, at the start of every loop, an entirely new variable is created named i, containing one of the values in valueArr. Once the loop ends this variable is destroyed. Notably, i is not directly the value in valueArr - modifying it does nothing - other than affect this one loop if you use i later in within the block. It does not modify the contents of valueArr.
Hence why you get the warning: i = -1 does nothing - you change what i is, and then the loop ends, which means i goes away and your code hasn't changed anything or done anything, which surely you didn't intend. Hence, warning.
It's not entirely clear what you want to do here. If you intend to set all values in valueArr to -1, you want:
for (int i = 0; i < valueArr.length; i++) valueArr[i] = -1;
Or, actually, you can do that more simply:
Arrays.fill(valueArr, -1);
valueArr[i] = -1 changes the value of the i-th value in the valueArr array to -1. for (int i : valueArr) i = -1; does nothing.

Java - printing a variable that was declared inside an if statement

So I'm trying to declare an integer variable inside an if/else statement, and print it out, outside of it. Something like this:
int x;
int a = 1;
if (a == 1)
{
int x = 5;
}
System.out.println(x);
This is just an example of what I'm trying to do, as I don't have the actual code with me, and i don't want to redo it all over. Although it shouldn't matter really, as the example is exactly what i need, only with different variable values and names (but it's still an integer). At first i just declared and initialised the variable inside the if/else statement, but then I was told I need to declare it outside the statement... So I did that, then initialised it within the statement, and then proceeded to call on it later on. However I'm still getting an error, either it says the variable hasn't been initialised, or if I assign a value to it (x) then update it inside the statement, the error i get is that it has already been declared. Any help would be appreciated, thanks.
Yes. Local variables needs to be initialize before they use. Where as instance variables initialize to default values if you didn't initialize them before use.
If you are curious about the reason? click here to know
Coming back to your question again,
Because consider the below scenario
Follow comments.
int x; // declared with no value
int a = 0;
if (a == 1) // this is false
{
x = 5; // this never executed
}
System.out.println(x); // what you are expecting to print here ?
Hence you need to initialize with a value. For ex : initialize it with zero and change it later on based on a condition
int x=0;
int a = 1;
if (a == 1)
{
x = 5;
}
System.out.println(x);
Simply assign the int x = 0 before your if-statement, then instead of redeclaring x as an integer equal to 5, set x equal to 5 inside your if statement.
The point is that you declared x above. So remove int before x inside the if-statement. Then it works.
int x;
int a = 1;
if (a == 1) {
x = 5;
}
System.out.println(x);
Implicitly an integer is initiated with 0. If you want to be sure just write
int x = 0;
your code here
int x = -1;
int a = 1;
if (a == 1)
{ // here begins inner 'area' for declared variables
x = 5;
}// and here ends
System.out.println(x);
OK, my bad! I wanted him to wonder why and try some other ways of writting it and letting him get 'hit' by IDE errors.
So Mr. Unknown as far as you declare variable 'inside' if statement it is visible only across that statement! So basicly if You want to do something with variable inside if statement, and have results outside of it, You need to declare it outside the statement making it having wider range of accessibility! If You have any questions don't hesitate to ask ;)
P.S. Watch out for re-declaring variable with the same name like You tried to do here, it's nasty bug to find =)
Thank you all for the answers, I realized I made 2 minor mistakes that didnt allow it to work, I (in most attempts) didn't declare a value for x before the if statement, and I had 'int' in front of x inside the if statement, which caused the re-deceleration error. So yea, thank you for the quick answers :)

Variable not seemed to be initialized

import java.util.Scanner;
public class finnTall {
public static void main(String[]args){
int antallTall;
int antallLest;
double nesteTall;
double minsteVerdi;
double nestMinsteVerdi;
Scanner tast = new Scanner(System.in);
System.out.println("Hvor mange tall?");
antallTall = tast.nextInt();
tast.nextLine();
antallLest= 1;
System.out.println("Skriv første tall: ");
minsteVerdi = tast.nextDouble();
tast.nextLine();
for(antallLest=1;antallTall>antallLest;antallLest++){
System.out.printf("Skriv %d. tall: ",antallLest+1);
nesteTall = tast.nextDouble();
tast.nextLine();
if(nesteTall>minsteVerdi)
nestMinsteVerdi=nesteTall;
if(nesteTall<minsteVerdi)
nesteTall = minsteVerdi;
if(nesteTall>minsteVerdi && nesteTall<nestMinsteVerdi)
nestMinsteVerdi = nesteTall;
}
System.out.printf("Minste verdien av tallene du har oppgitt er: %f\n",minsteVerdi);
System.out.printf("Nest minste verdi av tallene du har oppgitt er: %f\n",nestMinsteVerdi);
tast.close();
}
}
It's a program supposed to calculate the lowest and second lowest number that the user provides.
For some reason, it says that the local variable nestMinsteVerdi is not initialized, and I can't seem to figure out why or where the fault is. I have been struggling with this for a good 2 hours.
Thanks in advance.
In Java, a local variable needs to have a definitely assigned value before its value is accessed.
You declare your local variable without assigning it a value. This is okay in Java, because the compiler will ensure that you give it a value before using it.
double nestMinsteVerdi;
Then set it if a condition is true:
if(nesteTall>minsteVerdi)
nestMinsteVerdi=nesteTall;
Then access it in the conditional of an if statement. But if the condition above were false, the value of nestMinisteVerdi would not yet be assigned.
if(nesteTall>minsteVerdi && nesteTall<nestMinsteVerdi)
nestMinsteVerdi = nesteTall;
Since there's at least one way for the code to execute in which no value is assigned, the compiler complains. This is a good thing. Accidentally uninitialized variables can be a frequent source of defects.
From the Java Language Specification, Chapter 16: Definite Assignment:
The idea behind definite assignment is that an assignment to the local variable or blank final field must occur on every possible execution path to the access.
Andy Thomas's answer is correct. You do not assign a value to the variable.
double nestMinsteVerdi;
The compiler will not allow you to run because the only assignment is within a conditional that could conceivably fail, and if it were to fail, the variable would not be assigned a value. Since code can't be compared to a variable with no value, this would break execution, so the compiler will not allow it.

Confused over initialisation of instance variables

I'm studying up for the SCJP exam, upon doing some mock tests I came across this one :
It asks what is the output of the following :
class TestClass
{
int i = getInt();
int k = 20;
public int getInt() { return k+1; }
public static void main(String[] args)
{
TestClass t = new TestClass();
System.out.println(t.i+" "+t.k);
}
}
I thought it would be 21 20, since t.i would invoke getInt, which then increments k to make 21.
However, the answer is 1 20. I don't understand why it would be 1, can anyone shed some light on this?
The variables are initialized from top to bottom.
This is what happens:
Initially both i and k have the (default) value 0.
The value computed by getInt() (which at the time is 0 + 1) is assigned to i
20 is assigned to k
1 20 is printed.
Good reading:
The Java™ Tutorials: Initializing Fields
jvm will follows like this,
1.identification for non-static members from top to bottom
2.executing non-static variables and blocks from top to bottom
3.executing the constructor......
in the first step jvm will provide default values..on that time variables in readindirectly write only state..

beginner java, help me fix my program?

I am trying to make a calculator for college gpa's. I cut out all like 20 if statements that just say what each letter grade is. I fixed my first program for anybody looking at this again. The program now works, but regardless of the letters i type in the gpa it returns is a 2.0 . If anybody sees anything wrong it would be very much appreciated...again. Thanks
import java.util.Scanner;
public class universityGPA {
public static void main(String args[]){
int classes = 4;
int units[] = {3, 2, 4, 4};
double[] grade = new double[4];
double[] value= new double[4];
int counter = 0;
double total = 0;
double gpa;
String letter;
while(classes > counter){
Scanner gradeObject = new Scanner(System.in);
letter = gradeObject.next();
if(letter.equalsIgnoreCase("A+") || letter.equalsIgnoreCase("A")){
grade[counter] = 4;
}
if(letter.equalsIgnoreCase("F")){
grade[counter] = 0;
}
value[counter] = grade[counter] * units[counter];
counter++;
}
for(int i = 0; i < classes; i++ ){
total += value[i];
}
gpa = total/classes;
System.out.println("You gpa is " +gpa);
}
}
You forgot to initialize grade. The NullPointerException is telling you that grade is null. The exception is thrown the first time you try to use grade, in the statment grade[counter] = 4;. Allocate as much space as you need with new.
Initialization of grade can be done statically as well dynamically:
double []grade = new double[4];
or
double []grade = new double[classes];
Do the same for value as well.
Here are a few pointers for cleaning up your code:
Try to be more consistent with your formatting. Make sure everything is properly indented and that you don't have lingering spaces at the beginnings or endings of lines (line 18).
You should declare variables as close to the first spot you use them as possible. This, along with making your code much more readable, minimizes the scope. For instance, on line 18, you initialize letter, but it is never used outside the scope of the while statement. You should declare the variable right there, along with the initializer (String letter = gradeObject.next()).
Declaring arrays in the type name[] form is discouraged. It is recommended to use the type[] name form instead.
Try to separate your program into distinguished sections. For instance, for this program, you can clearly see a few steps are involved. Namely, you first must grab some input, then parse it, then calculate the return value. These sections can be factored out into separate methods to clean up the code and promote reuse. While it may not seem to yield many benefits for such a simple program, once you start working on larger problems this organization will be absolutely mandatory.
NullPointerException means you are trying to access something that does not exist.
Since your grade[] is null, accessing it on line 21 by grade[counter] actually means you are accessing something that has yet to be created.
You need to initialize the array, so it actually has an instance.

Categories

Resources