Local variable may not have been initialized in my For loop - java

Trying to make a for loop where a user inputs 6 numbers. Then each number is validated to see that it is positive. Then they are all added up for a subtotal.
On my last line count += itemPrice; I'm getting an error on count saying "The local variable may not have been initialized." A buddy of mine can't seem to figure out why as well and wondering what is up with that.
public static double namehere() {
double count;
for (int x = 0; x < 6; x++)
{
Scanner input = new Scanner (System.in);
System.out.println ("Price of Item: ");
double itemPrice = input.nextDouble();
while (itemPrice < 0.01)
{
Scanner input2 = new Scanner (System.in);
System.out.println ("Price of Item: ");
itemPrice = input.nextDouble();
}
count += itemPrice;
}

double count; // not initialized
double count = 0; // initialized
Local primitive variables are not set to 0 by default, so they must be explicitly initialized.

As the error message says, your count variable is not initialized. To solve the error, initialize with a default value, like 0.
Note: the local variables are not initialized implicitly not like class members.

The purpose of local variables is different than the purpose of instance variables. Local variables are there to be used as part of a calculation; instance variables are there to contain state. If you use a local variable without assigning it a value, that's almost certainly a logic error, and hence, compiler complains..

Related

Error: variable might not have been initialised in my CellPhoneBill program

I am getting these 3 errors after compiling .. Pls help and thnx in advance..
error: variable ac might not have been initialized
tcws= cm+tm+ac+am+ta;
error: variable am might not have been initialized
tcws= cm+tm+ac+am+ta;
error: variable ta might not have been initialized
tcws= cm+tm+ac+am+ta;
My code:
import java.lang.*;
import java.util.Scanner;
class CellPhoneBill {
public static void main(String[]args) {
double cm ,tm ,ac, am, ta, tcws, tax, taxpluscost ;
Scanner s=new Scanner(System.in);
System.out.print("Enter the number of minutes and also enter the number of text messages ");
cm= s.nextDouble();
tm= s.nextDouble();
if(cm<=50&& tm<=50) {
System.out.print("Base charge= $15.00"); }
else if(cm>50 && tm>50) {
System.out.println("Enter no of additional call minutes (if any) and additional messages(if any) ");
ac=s.nextDouble();
am= s.nextDouble();
cm=0.25* ac;
am=0.15*am;
System.out.println("Additional call charges = " +ac);
System.out.println("Additional message charges = " +am);
ta=ac+am;
System.out.println("Total Additional charges = " +ta);
}
else if(cm>=0&& tm>=0) { System.out.println("911 Call charges =$0.44" );
}
else {
tcws= cm+tm+ac+am+ta;
System.out.println("Total cost without Sales Tax ="+tcws);
tax=( 5/100.00*(tcws));
System.out.println(" 5% Sales Tax ="+tax);
taxpluscost=tcws+tax;
System.out.println("Total cost Including 5% Sales Tax ="+taxpluscost);
}
}
}
It means that the variables ac, am and ta have not been assigned any value. You cannot sum variables that haven’t got any value.
For the fix, it depends on what you are trying to obtain. Maybe you need to do ac=s.nextDouble(); as in some of the other cases to read a value from the user. Or maybe you just need to do ac = 1.0; or whatever the appropriate value would be. And the same for the other two variables, of course.
Possibly you intended a different if-else structure where the values assigned to the three variables in one if branch should also be used in the last else part?
For Auto initialization you can declare them in your class as instance variable instead in static method.You can use the same variable in your static method then.
Your scanner only prompts the user for two values initially, neither of which are ac or am. Thusac = s.nextDouble() and am = s.nextDouble () aren't actually assigning values to ac and am
In java references to primitive data types are stored in the same register as the variable.
double a = 12.345;
Initializes a variable a and sets it to the value of 12.345.
You must initialize your variables prior to using them lest you get an error.
edited for corrections

How do I pass these integers to the method below it?

I'm confusing myself here. My goal was to make a simple program that took the number of values the user wants to average, store them in an array (while adding them together) and finally giving the average of these numbers.
My thing is, I am trying to understand the concept of multiple classes and methods as I am new so I tried using another class just do do all the work, while the Main class would just create the object from the other class, and then run their methods. Maybe I am asking something impossible. Take a look at my code.
This is my Main class:
public class Main
{
public static void main(String[] args)
{
System.out.println("Please enter numbers to average together");
OtherClass averages = new OtherClass();
averages.collectNumbers();
averages.AverageNumbers();
}
}
Now I am not sure if anything goes in those parameters, or if I can even use "averages.AverageNumbers();" without creating another object with "OtherClass" called something else? I am pretty sure it's legal though.
Here is my other class for this project entitled "OtherClass"
import java.util.Scanner;
public class OtherClass // using this to name obj
{
public void collectNumbers() //name of our method that does things
{
Scanner sc = new Scanner(System.in);
System.out.println("how many integers would you like to average? ");
int givenNum = sc.nextInt();
System.out.println("Alright, I will average " + givenNum + " values. \nPress enter after each:");
int[] numCollect = new int[givenNum];
int sum = 0;
for (int i = 0; i < numCollect.length; i++)
{
numCollect[i] = sc.nextInt();
sum = sum + numCollect[i];
}
System.out.println(sum);
}
public int AverageNumbers(int givenNum, int sum)
{
int average = sum / givenNum;
System.out.println(average);
return average;
}
}
So when I run this now with the the method AverageNumbers, it does not work. I am suspecting that maybe I am passing in the integers wrong? I have been toying with it for about an hour now, so I am asking for help. How do I make this work?
This will work if you declare sum and givenNum as fields of your OtherClass, instead of as local variables. So, before the collectNumbers method, write
private int sum;
private int givenNum;
and remove the declarations of these two variables inside collectNumbers. So, for example, instead of
int givenNum = sc.getInt();
you'll just have
givenNum = sc.getInt();
because the variable already exists. Also change the declaration of the averageNumbers method to
public int averageNumbers()
because you no longer need to pass those two values in to this method.
This is the archetypical example of using the objects of a class to carry a small amount of data around, instead of just using a class as a way to group methods together. The two methods of this class work with sum and givenNum, so it makes sense to store these in each object of this class.
Lastly, in your averageNumbers method, you have an integer division, which will automatically round down. You probably want a floating point division instead, so you could write
double average = (double) sum / givenNum;
which converts sum to a double-precision floating point number before the division, and therefore does the division in floating point, instead of just using integers. Of course, if you make this change, you'll need to change the return type of this method to double too.

My variables won't count because the compiler thinks they may not be spawned

I'm making a program for doing sin, cos, tan function and am in progress
However, because I used an if-else statement, it thinks that my variable (stepc) may not be initialized.
Since trig graphs are repetitive, I'm trying to make all graphs under the range of 0 to 360.
import java.util.Scanner;
public class Trigonometry
{
public static void main(String[]args)
{
double answer;
double x;
double stepa;
double stepb;
double stepc;
double stepd;
Scanner scanner = new Scanner (System.in);
System.out.print("Enter number");
x = scanner.nextDouble();
stepa = Math.abs(x);
stepb = stepa / 360 ;
if(stepb > 1) // <-- my functions for step c
{
while (stepb>1)
{
stepc = stepb - 1;
}
}
else
{
stepc=stepb;
}
stepd=stepc*360; // <-- won't consider step c
System.out.println( stepc );
}
}
----jGRASP exec: javac -g Trigonometry.javaenter code here
Trigonometry.java:34: variable stepc might not have been initialized
stepd=stepc*360;
^
1 error
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Initialize stepc to some default value when you define it.
You have to assign a value to it before you can use it.
Have you tried giving values to your step[abcd] variables when you initialize them?
Also, if stepb > 1, your code, as written, will never terminate. Do you see why?
As the others have noted, use:
double answer;
double x;
double stepa;
double stepb;
double stepc = 0;
double stepd;
edit: no harm in assigning values to the other variables too.
also, be aware that this loop is probably running infinitely:
while (stepb>1)
{
stepc = stepb - 1;
}

Variable uninitialized - must I set a variable, rather than just add to it in an if statement?

I'm trying to build a basic weight calculator and came across "variable weightOut might not have been initialized" error. Google seems to indicate that this is because I need to initialize "weightOut" rather than just set it " = weightIn * .78 " . Is this true? Here is my code.
Scanner keyboard = new Scanner(System.in);
int weightIn, planetNumber;
double weightOut;
System.out.print("What is your weight? ");
weightIn = keyboard.nextInt();
System.out.println("I have information for the following planets: ");
System.out.println(" 1. Venus ");
...
System.out.print("What planet are you going to? ");
planetNumber = keyboard.nextInt();
if( planetNumber == 1 )
{
weightOut = weightIn * 0.78;
}
...
System.out.println("Your weight would be " + weightOut +
" on that planet.");
Local variables are not initialized with default values.Local variables should be initialized before use .
double weightOut = 0.0;
What if the if statement never really executed at run time ? The compiler is actually worried that in case during run time the local variable fails to get a value and you use it some where else , what value it should have given it doesn't have a default value !
In java method/local variables should be initialized. Uninitialized variables can give unexpected results and hence this is raised. In your code the value of weightOut will never be set if the enclosing if conditions is not met. You need to initialize the following variable with some default value:
int weightIn = 0;
int planetNumber = 0;
double weightOut = 0.0d;
What value will the the variable have if you don't enter the if-branch?
To fix this, add an else-branch at the end:
if (...)
myVar = x;
else if (...)
myVar = z;
else
myVar = y;
Setting the value in an else-branch rather than setting some default initial value not only makes the compiler happy but also prevents you from committing the error that the compiler is complaining about: if at some later point you add code that uses the variable before its correct value is set in the if statement you would still get an error message from the compiler and not an unexpected result when running the program.
You need to initialize "weightOut" to 0, because local variable can not be used without initializing.
As in your case you are assigning value in if condition and that one is not valid because in java value of local variable is decided at run time. That is the reason u are getting error.
What if the planet number is 0?
You should do:
double weightOut = 0;

exponential growth in java, return type array of doubles

Im working on a CS assignment and Im having a little trouble understanding how to output an array of doubles that represent the amt of money in a bank account at increments of time given a user specified growth rate. I have a main method that asks the user for initialAmount of $, a growthRate and the number of time intervals (denoted iA, gR and nP for inital Amount, growth Rate and number of Periods). this method then calls another method which is of return type double[]. My issue is with the code inside my for-loop, it compiles fine but outputs gibberish. heres the code:
import java.util.Scanner;
public class Benford {
public static double[] generateBenfordNumbers (double iA, double gR, int nP) {
double[] bankStatement = new double[nP];
for (int i = 0; i<nP; i++) {
bankStatement[i] = (iA*(Math.pow((1+(gR)), (i++))));
}
return bankStatement;
}
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double iA;
double gR;
int nP;
System.out.print("What is the initial amount of money that you are starting with? : ");
iA = scan.nextDouble();
System.out.println();
System.out.print("What is the amount of growth per time period? : ");
gR = scan.nextDouble();
System.out.println();
System.out.print("How many time periods would you like to use? : ");
nP = scan.nextInt();
System.out.println();
generateBenfordNumbers(iA, gR, nP);
System.out.print(generateBenfordNumbers(iA, gR, nP));
}
}
In the line
bankStatement[i] = (iA*(Math.pow((1+(gR)), (i++))));
i++ increments i a second time. You probably want:
bankStatement[i] = (iA*(Math.pow((1+(gR)), i + 1)));
or, if we clean it up,
bankStatement[i] = iA * Math.pow(1 + gR, i + 1);
i + 1 returns a value 1 greater than that of i, but does not actually increment the variable itself.
Also, do you really have to use Math.pow each time? Can't you just manually set the first element of your array to iA and subsequently use bankStatement[i-1] to compute bankStatement[i]? Doing something like this will probably improve your program.
i is incremented twice : at loop level and into the body
The gibberish output looks like this:
[D#1b67f74
which is s double array text representation. You could use:
System.out.print(Arrays.toString(generateBenfordNumbers(iA, gR, nP)));
You should not be incrementing i inside your call to Math.pow. This is because you already increment it in your for loop. The result is that elements of your array are getting skipped and not set. This is probably where the gibberish-ness is coming from.
You probably want to change:
bankStatement[i] = (iA*(Math.pow((1+(gR)), (i++))));
To:
bankStatement[i] = iA*Math.pow(1+gR, i);
Also, as an aside, you generally shouldn't use so many parenthesis because it makes it hard to read. If you're not sure what the order of operations is, look it up.
What the others said, you're incrementing i twice so I'm not going to repeat that. I just want to add that brackets are good to organize formulas and to ensure correct execution order of calculations, but if you overuse them, they can obfuscate the intention of your program and they may make the problem you're looking for harder to spot. Compare
bankStatement[i] = iA * Math.pow(1.0 + gR, i+1);
with
bankStatement[i] = (iA*(Math.pow((1+(gR)), (i))));
See what I mean?
EDIT - following ARS very valid remark about the initial value of i, I changed the cleaned up statement.

Categories