When I type this code,
import java.util.*;
public class Example{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("Input an integer : ");
int num = input.nextInt();
int y;
if(num>100){
y=200;
}
if(num<100){
y=200;
}
if(num==100){
y=200;
}
System.out.println(y);
}
}
There is an error saying "variable y might not have been initialized." Why?
CodePudding user response:
This error occurs when we are trying to use a local variable without initializing it. ( accessing it in the print statement) In your example, you have only written the if statement and compiler will not be able to detect it. To help the compiler, you can either use , the if else block which covers all the cases and it convinces the compiler or you can initialize it with value 0.
int y;
if(num>100){
y=200;
}
else if(num<100){
y=200;
}
else{
y=200;
}
System.out.println(y);
CodePudding user response:
In your code, you are declaring y as a "not initialized" variable int y;. At that point, y is not defined. If you change it to int y = 0; it will be fine.
The compiler does not know when y will be initialized, all it knows is that there are some if statements involving variable y and that variable y is just blank space, thus making it "impossible" to evaluate variable y.
Scanner input = new Scanner(System.in);
System.out.print("Input an integer: ");
final int LIMIT = 100; // less magic numbers
int input = input.nextInt();
int result = 0;
if(input > LIMIT){
result = 200;
}
if(input < LIMIT){
result = 200;
}
if(input == LIMIT){
result = 200;
}
System.out.println(result);
I modified your code a bit to solve the "not initialized" part. Also added a final variable for the 100 value since it is considered a good practice to name every value (no magic numbers).
You can also reduce code on this by changing the if statements a bit:
final int LIMIT = 100;
if (input == LIMIT || input < LIMIT || input > LIMIT) {
result = 200;
}
CodePudding user response:
import java.util.*;
class Example{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
System.out.print("Input an integer : ");
int num=input.nextInt();
int y=0;
if(num>100){
y=200;
}
if(num<100){
y=200;
}
if(num==100){
y=200;
}
System.out.println(y);
}
}
