java Local variable not initializing outside if-statement - java

Eclipse says that the variable age, agirl and aboy may not have been initialized. I initialized the variables before the first if statement and they got values in the if-statement. When I want to use them in the next if-statement eclipse says the local variables may not have been initialized.
Here is my code:
import java.util.Scanner;
class Main{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String define;
int aboy, agirl, age;
System.out.println("Are you a boy or a girl?");
define = input.next();
if (define.equals("boy")){
System.out.println("What is your age?");
aboy = input.nextInt();
age = aboy;
}else if (define.equals ("girl")){
System.out.println("What is your age?");
agirl = input.nextInt();
age = agirl;
}else
System.out.println("wrong answer");
if (agirl >= 18 || aboy >= 16){
System.out.println("You are a " + define + " and you are " + age + " years old");
}
}
}

This line
int aboy, agirl, age;
contains declarations, not initializations. Java will not initialize a local variable for you, and there is an execution path (the else) where nothing is ever assigned to those variables, then you attempt to reference their nonexistent values.
You must set values to them before you use them, in all execution paths. Initialize them to something when you declare them.

Not only may you have an uninitialized variable, you're guaranteed to.
Look at your control flow: You first ask for a value for define, and then you execute exactly one of the blocks. If define is "boy", you don't initialize agirl; if define is "girl", you don't initialize aboy, and if define doesn't match either, you don't initialize any of your variables at all.
It looks like you are trying to cleverly combine the functions of a boolean and an int by having "magic" values in your ints. This is poor design because it's not clear how the magic works, but you can make your example run by initializing all of your int values to 0:
int aboy = 0, agirl = 0, age = 0;

Initializing is assigning the variable a value. Declaring is creating the variable. They are not the same.
The reason you need to initialize the variables is because it is possible they will not be initialized. All the if statements could be false, thus you need to give them a default value.

Related

User inputs his first name inside a while loop how do I display the name later? [duplicate]

I'm a new programmer trying to practice by making a game.
I want the player to be able to set their own name, as well as answer yes or no as to whether that name is correct.
I did this by using a while loop.
However, since the name is initialized inside the loop, I cannot use it outside. I was wondering if there was anyway to do so.
My code is probably very basic and messy. I apologize for that.
Scanner input = new Scanner(System.in);
String name;
int nameRight = 0;
while (nameRight == 0) {
System.out.println("What is your name?");
name = input.nextLine();
System.out.println("So, your name is " + name + "?");
String yayNay = input.nextLine();
if (yayNay.equals("yes") || yayNay.equals("Yes")) {
System.out.println("Okay, " + name + "...");
nameRight++;
}
else if (yayNay.equals("no") || yayNay.equals("No")) {
System.out.println("Okay, then...");
}
else {
System.out.println("Invalid Response.");
}
}
So basically, I want String name to be initialized inside the loop, so I can use it outside the loop.
The scope of a variable, limits the use of that variable to the scope it is defined in. If you want it used in a broader scope, declare it outside the loop.
However, since the name is initialized inside the loop, I cannot use it outside.
You have defined the variable outside the loop, so the only thing you need to do is to initialize it, as the error message you should get suggests.
String name = "not set";
while(loop) {
name = ...
if (condition)
// do something to break the loop.
}
// can use name here.
The basic problem is that the compiler cannot work out that the variable will be set in all possible code paths. There is two ways you can fix this without using a dummy value. You can use a do/while loop.
String name;
boolean flag = true;
do {
name = ...
// some code
if (test(name))
flag = false;
// some code
} while(flag);
or drop the condition, as you don't need a counter.
String name;
for (;;) {
name = ...
// some code
if (test(name)) {
break;
// some code if test is false.
}
NO, it wouldn't be possible as the scope of the variable declared in the loop is limited to the loop. So the variable is not longer accessible.
while(i < 10){
int x = 2;
i++;
}
Now, the scope of x would be from the point at which it is defined to the end of the enclosing block. So the variable here would be created and destroyed 10 times if i starts from 0.
First there's the "scope", this is the issue you're touching at the moment. The way you have done this so far seems to be a good way of doing it and you WILL be able to use/access the name variable from anywhere in the code after line 2 from what you have linked.
The scope basically says, you can use the variable inside the curly brackets {} that you DECLARED it inside. I assume that you have your code inside some main method at the moment, thus you can access the name variable from anywhere after the line
String name;
as long as you don't try to use it after the closing }, corresponding to a opening { that occurred before name is declared.
SOLUTION: What you have to do to use a variable outside a loop, is to declare it before the loop begins, you don't have to initialize the variable before, but you have to initialize it before you try to use it for anything. In general, if you need to access the variable in a wider area, you must declare that variable before you enter the not-so-wide area.
Notice that by declaring I mean creating the variable reference by using "String" in front of "name". Don't confuse it with initializing it or assigning a value to it, that has nothing to do with the scope, only declaration sets the scope.

Am trying to recall the output of line 8 but still having problems

am trying to refer back to line 8 but don't know how, sorry am new to Java.
I've tried many approaches but still hitting a wall, pls what should I do.
package Interview;
import java.util.Scanner;
public class Interview {
public static void main(String[] args) {
System.out.println("hello,please what is your name:");
System in = scanner(System.in);
String Input=in.nextLine();
System.out.println("well then welcome to startechz "+Input);
System.out.println("Are you a male or female:");
String Input=in.nextLine();
if (Input=male)
//recall outprint from line 8
System.out.println("once again, welcome mr"+Input of Line8);
else {
System.out.println("once again,welcome mrs"+Input of Line8);
}
}
there many syntax error on your code it would be better to use ide
change this
System in = scanner(System.in);
to
Scanner in = new Scanner(System.in);
you can not redefine same variable again you have to statement
that looks like this
String Input=in.nextLine();
to solve this either use this
String newInput=in.nextLine();
or just assign new value to the same variable (of course of course if you do not want to use the old one again) like that
Input=in.nextLine();
in java to compare value you use double = sign like
Input==male
single = are used to assign value like int value = 5;
you can use == with primitive type only it will work but for reference type it will not work as in your case you use String with is reference type
why it did not work with reference type cause it will compare the reference address (the address for the object in memory (to be accurate it not the physical address but think of it like that))
so use the equal method
like
if (Input.equals("male")) // you forget also to make male as string you forget the double quotations
Change
if (Input=male)
to
if(Input.equalsIgnoreCase("male")) // allows case independent compare
Use equals or equalsIgnoreCase to compare strings.

Trouble Getting My Do...While Loop To Work - Java

I'm trying to make it for that the program will continue to request input of a 5 digit number until the user gives a 5 digit number. When I run the following:
//import scanner to read keyboard input
import java.util.Scanner;
class NumberInverter {
public static void main(String[] args) {
//create a new Scanner object in the memory that reads from the input System.in
Scanner keyboard = new Scanner(System.in);
//display message propmt and input for number
//conditional statement loop to check if the length is any number other than 5
do {
System.out.print("Enter any 5 digit whole number you wish to invert!");
int num = keyboard.nextInt();
int numSize = String.valueOf(num).length();
} while(!isValid(numSize));
}
private static boolean isValid(int numSize){
if(numSize != 5){
System.out.println("Oops! Looks like you gave a number that isn't exactly a 5 digit whole number. Try again!");
return false;
} else return true;
}
}
I get the following error:
NumberInverter.java:20: error: cannot find symbol
} while(!isValid(numSize)); ^
symbol: variable numSize
location: class NumberInverter
1 error
I've tried a bunch of different things, can anyone fluent in java help me out I'm very new?
Thanks ahead of time!
The variable numSize is not in the same scope as the while condition check.
In Java, any variable declared inside a block (a region surrounded by {}) cannot be accessed outside of that block. In this case, since you are declaring numSize right inside the loop, the loop's condition (which is outside that block) cannot access it. Each block creates something called a "block scope", and variables created in there cannot be accessed outside it.
The fix for this is very simple: Declare the variable in the same scope as the while loop. This can be done by putting it right above the do. Notice that you only need to int numSize;, outside, once. You don't put int when you are assigning to it inside the loop, you just do numSize = .... since you are assigning to a previously-declared variable.
You can still assign to the variable from inside the loop, but since it was originally declared outside the loop, stuff outside the loop can access it.
int numSize;
do {
System.out.print("Enter any 5 digit whole number you wish to invert!");
int num = keyboard.nextInt();
numSize = String.valueOf(num).length();
} while(!isValid(numSize));
Some more information about scopes can be found at What is 'scope' in Java?.
Num size is declared inside the loop scope, you're trying to access it outside that scope. For this to work, declare numSize just before the do statement and assign it within the loop. This way, the variable is visible in the whole statement and also inside the loop (for assignment).
int numSize;
do {
// The rest of your code, all variables declared here are
// gone outside the brackets, however you can access the ones
// in outer scopes.
numSize = String.valueOf(num).length();
} while(!isValid(numSize));
See this for more information about different types of scope: https://www.geeksforgeeks.org/variable-scope-in-java/
Create a local variable numSize.
For exemple :
//import scanner to read keyboard input
import java.util.Scanner;
class NumberInverter {
public static void main(String[] args) {
//create a new Scanner object in the memory that reads from the input System.in
Scanner keyboard = new Scanner(System.in);
int numSize;
// int numSize;
//display message propmt and input for number
//conditional statement loop to check if the length is any number other than 5
do {
System.out.print("Enter any 5 digit whole number you wish to invert!");
int num = keyboard.nextInt();
numSize = String.valueOf(num).length();
} while(!isValid(numSize));
}
private static boolean isValid(int numSize){
if(numSize != 5){
System.out.println("Oops! Looks like you gave a number that isn't exactly a 5 digit whole number. Try again!");
return false;
} else return true;
}
}

Variables in a do while loop

Below is some code asking the user to input an integer.
public int getValidInput() {
Scanner user_input = new Scanner(System.in);
do {
System.out.println("Enter an integer >=1 and <=10: ");
int number = user_input.nextInt();
} while (number > 10 || number < 0);
return number;
}
The code as shown does not work although when I initialise number outside the do command i.e. set it to int number; and then in the do loop set number = user_input.nextInt(); it does. Why does it work in one case and not the other?
Because in Java, variables are scoped to the block in which they're declared. In your example, the int number = is within the do...while block, and so the variable only exists within that block.
By moving the declaration out of the block, into the block for the method, the variable exists for the method's entire block (including nested blocks).
Your problem is that you have defined number inside your loop. Variables are scoped in Java, so variables declared inside loops or if statements are not accessible outside those loops or if statements. You can fix your code, simply by moving the declaration, as shown below:
public int getValidInput() {
Scanner user_input = new Scanner(System.in);
int number;
do {
System.out.println("Enter an integer >=1 and <=10: ");
number = user_input.nextInt();
} while (number>10 || number < 0);
return number;
}
The curly braces {} of the do-while open up a so called scope (they always do, wether in methods or loops or ifs). Any declaration inside a scope is only visible while you are within that scope, and also in any inner scope opened within the scope.
The condition of your while is outside the curly braces, so it does not see any variable declared within them. If you put the int number; before the do, it's on the same scope level like the while condition, so it, along with the value it gained inside the loop, is visible to the expressions in the condition.
Conditions are used to enter a body from outside that body, so the variable which decides the truth value of condition has to exist before the body.
And as the body block of do-while loop is the code to be executed, therefore the code which decides to execute it must be other than itself.
The scope of a variable restricted to {}. outside of that braces you cannot access. When you initialised it on top it access across both do and while as the scope is increased.

Java Variable will not initialize in an if statement?

I have initialized and declared the variable "average." I do not understand why it won't compile. Does it have to do with the fact that it's in an if else? I've already tried
"|| null" and that is not taking either. What to do?
// declare variables
Scanner keyboard = new Scanner (System.in);
String given;
String middle;
String sur;
String truefalse;
boolean bool;
int exam1;
int exam2;
int exam3;
double average;
// get input
System.out.println("*************** Grade Computer *************");
System.out.println("Enter the student's first name: ");
given = keyboard.nextLine();
System.out.println( "Enter the student's middle initial: ");
middle = keyboard.nextLine();
System.out.println( "Enter the student's last name: ");
sur = keyboard.nextLine();
System.out.println( "Enter EXAM 1 Grade: ");
exam1 = keyboard.nextInt();
System.out.println( "Enter EXAM 2 Grade: ");
exam2 = keyboard.nextInt();
System.out.println( "Enter EXAM 3 Grade: ");
exam3 = keyboard.nextInt();
keyboard.nextLine();
System.out.println( "Bonus work completed [true/false]");
truefalse = keyboard.nextLine();
// adjust exam scores if necesssary
if (truefalse == "true")
{
bool = true;
exam1 = keyboard.nextInt();
exam2 = keyboard.nextInt();
exam3 = keyboard.nextInt();
}
else
{
average = ((exam1+exam2+exam3)/3);
}
Why is the compiler saying
"variable average might not have been initialized"?
You declared your variable but did not strictly initialize it. It is only initialized if the logic of your program dictates that the line average = ((exam1+exam2+exam3)/3); is hit. This doesn't happen if truefalse == "true".
In order to have Java compile it, you can do one of two things.
Initialize your variable to some default value when you declare it, eg double average = 0;
Make sure that no logical pathway precludes the possibility that the variable is initialized. That is, no matter what happens, it gets initialized.
The first option is better. It keeps your code cleaner and more logical, thus easier to maintain. The second option is more implicit than explicit. You probably shouldn't have to go walking through the logic yourself to see how it works out.
You can initialize the double variable average to 0 when you are declaring it.
double average=0;
Reason of this particular error is that you are trying to initialize the variable in if-else block. The variable will not be initialized if condition is not true. If you are using the variable further in your program, you will get run time errors. That is why Java compiler is letting you know that there are possibilities that the variable might be uninitialized
Furthermore it is always a good practice to initialize a local variable when you declare it.
You need to initialize average.
The compiler is complaining because your code might or might not ever reach the else block. Yet, if you use average when it hasn't been initialized, you get an error.
double average = null;
Alternatively, you can initialize average in the if block as well, because if the if block runs and the else doesn't you'll still have an initialized average at the end of the day and the compiler is happy :).
if (truefalse == "true")
{
average = //something;
bool = true;
exam1 = keyboard.nextInt();
exam2 = keyboard.nextInt();
exam3 = keyboard.nextInt();
}
else
{
average = ((exam1+exam2+exam3)/3);
}
Also, as a final note, a good rule of thumb is to use .equals() for any String and == for ints, characters, booleans etc.

Categories