Variable might not have been initialized error in an assignment for school
Hello All... I am very new to Java (started class about 2 weeks ago) and my current assignment has me a bit stumped on what I am doing wrong. I have put the code in this message for everyone to take a look at and offer advice or point me in the right direction on what I missed a step on. I appreciate any help you can offer.
The error is coming on line 39:
* Program: MathProgramExtra
* Author: Michael Stewart
* Date: August 22, 2010
* Program Purpose: This program is intended to display selection and iterative statements.
import javax.swing.*;
public class MathProgramExtra
public static void main (String[] args)
Object[] mathPossibilities = {"+", "-", "*", "/", "%"};
Object[] firstintegerPossibilities = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
Object[] secondintegerPossibilities = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
Object[] options = {"Yes, Please", "No, Thank You"};
String m;
String f;
String s;
int firstint;
int secondint;
int answer;
char ans = 'Y';
while(ans !='N')
System.out.println("ans in beginning of loop is :"+ans);
m = mathOp(mathPossibilities);
f = firstNum(firstintegerPossibilities);
s = secondNum(secondintegerPossibilities);
firstint = firstNumConversion(f);
secondint = secondNumConversion(s);
performMath(m, firstint, secondint);
add(m, firstint, secondint);
subtract(m, firstint, secondint);
multiply(m, firstint, secondint);
divide(m, firstint, secondint);
modulus(m, firstint, secondint);
printMath(answer);
ans = verifyAnswer(options);
System.out.println("ans in end of loop is :"+ans);
if (ans == 'Y')
continue;
else
break;
System.exit(0);
public static String mathOp(Object[] possibilities)
String sentence = "Please select a mathematical operation";
String m = (String)JOptionPane.showInputDialog(null, sentence, "Operation Question",
JOptionPane.PLAIN_MESSAGE, null, possibilities, "+");
return m;
public static String firstNum(Object[] possibilities)
String sentence = "Please select an integer";
String f = (String)JOptionPane.showInputDialog(null, sentence, "First Integer",
JOptionPane.PLAIN_MESSAGE, null, possibilities, "0");
return f;
public static String secondNum(Object[] possibilities)
String sentence = "Please select another integer";
String s = (String)JOptionPane.showInputDialog(null, sentence, "Second Integer",
JOptionPane.PLAIN_MESSAGE, null, possibilities, "1");
return s;
public static int firstNumConversion(String f)
int firstint = 0;
if(f.equals ("0"))
firstint = 0;
else if(f.equals("1"))
firstint = 1;
else if(f.equals("2"))
firstint = 2;
else if(f.equals("3"))
firstint = 3;
else if(f.equals("4"))
firstint = 4;
else if(f.equals("5"))
firstint = 5;
else if(f.equals("6"))
firstint = 6;
else if(f.equals("7"))
firstint =7;
else if(f.equals("8"))
firstint = 8;
else if(f.equals("9"))
firstint = 9;
else if(f.equals("10"))
firstint = 10;
return firstint;
public static int secondNumConversion(String s)
int secondint = 0;
if(s.equals("1"))
secondint = 1;
else if(s.equals("2"))
secondint = 2;
else if(s.equals("3"))
secondint = 3;
else if(s.equals("4"))
secondint = 4;
else if(s.equals("5"))
secondint = 5;
else if(s.equals("6"))
secondint = 6;
else if(s.equals("7"))
secondint =7;
else if(s.equals("8"))
secondint = 8;
else if(s.equals("9"))
secondint = 9;
else if(s.equals("10"))
secondint = 10;
return secondint;
public static int performMath(String m, int firstint, int secondint)
int answer = 0;
if (m.equals("+"))
answer = add(m,firstint, secondint);
if (m.equals("-"))
answer = subtract(m,firstint, secondint);
if (m.equals("*"))
answer = multiply(m,firstint, secondint);
if (m.equals ("/"))
answer = divide(m,firstint, secondint);
if (m.equals ("%"))
answer = modulus(m, firstint, secondint);
return answer;
public static int add(String m, int firstint, int secondint)
int answer;
answer = (firstint + secondint);
return answer;
public static int subtract(String m, int firstint, int secondint)
int answer;
answer = (firstint - secondint);
return answer;
public static int multiply(String m, int firstint, int secondint)
int answer;
answer = (firstint * secondint);
return answer;
public static int divide(String m, int firstint, int secondint)
int answer;
answer = (firstint / secondint);
return answer;
public static int modulus (String m, int firstint, int secondint)
int answer;
answer = (firstint % secondint);
return answer;
public static void printMath(int answer)
String message = "Your answer is:" + answer;
JOptionPane.showMessageDialog(null, message, "Alert", JOptionPane.INFORMATION_MESSAGE);
public static char verifyAnswer(Object[] options)
char ans = 'N';
int n = JOptionPane.showOptionDialog(null, "Would you like to enter another problem, Yes or No?", "Another Problem?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
switch(n)
case 0:
ans = 'Y'; break;
case 1:
ans = 'N'; break;
return ans;
mstew1979 wrote:
Thank you! I actually just got it working :)Cool. Here's a bit of advice, just in case you "fixed" it by making a common mistake: Don't just initialize a variable to a dummy value to make the compiler happy. Those "not initialized" errors usually point to a logic error. But just initializing the variable to 0, null, etc. at declaration, usually you're just masking the logic error so the compiler doesn't see it. You haven't fixed anything.
public String signum (int x) {
String result;
if (x > 0) {
result = "positive";
else if (x < 0) {
result = "negative";
return result;
}Here we have a compiler error, brought on by my logic error of forgetting to account for x being 0. The wrong way to fix it would be to blindly change the declaration of result to String result = ""; or == null;. The logic error is still there, but now it's hidden from the compiler. So we have an error at runtime instead--we don't get a valid response if we pass in 0. Runtime errors are much harder to debug than compile-time errors.
The correct response to the compiler's "not initialized" error is to look at our code more carefully and see what we might have missed. In this case, we would add and else clause that returns "zero".
Similar Messages
-
Variable might not have been initialized, but I can't get around it...
I'm getting a variable might not have been initialized error, and I know why, but I can't get around it. Basically, this snippet of my code is reading in a map file for a game. The first two lines of the map file are configuration information, and the rest is coordinates for the tiling graphics.
while ((str = in.readLine()) != null) {
if(!read_info){
//process first line: tileset image, size, playerpos
temp = str.split(",");
loadTileset(temp[0],32);
size_x = Integer.parseInt(temp[1]);
size_y = Integer.parseInt(temp[2]);
map = new Tile[size_x][size_y];
player.resetLoc(Integer.parseInt(temp[3]),Integer.parseInt(temp[4]));
//process second line: impassible
str = in.readLine();
temp = str.split("!");
impassable = new Point[temp.length];
for(int m=0;m<temp.length;m++){
tmp_coords = temp[m].split(",");
impassable[m] = new Point(Integer.parseInt(tmp_coords[0]),Integer.parseInt(tmp_coords[1]));
read_info = true;
} else{
temp = str.split("!");
for(int i=0;i<size_x;i++){
tmp_coords = temp.split(",");
boolean ti = true;
for(int p=0;p<impassable.length;p++){
map[i][j] = new Tile(Integer.parseInt(tmp_coords[0]),Integer.parseInt(tmp_coords[1]),true);
j++;
I'm not including everything.. this should make sense. Impassable is a Point[].
I can't say how big the Impassable list will be until it reads the second line of the map file. However, that happens in the first run-through of the file-reading processes.
Is there a try/catch statement I can use to get past this?If you set that variable to null you will fix this
error.
Object obj;to
Object obj = null;Beware this may cuase NullPointerExceptions, so you
should check this variable for being null before you
try to access it.That's usually the wrong way to approach this. Getting this compiler error is often a sign of a logic error. Only initialize the variable if it makes sense for the variable to have that value. Don't do it just to satisfy the compiler. -
Code problem, variable might not have been initialized..
I have a program I'm working on, I have to seperate file classes.. I have one that is mainly just the class and its functions, the other I'm triing to get to use the previously mentioned class, but it keeps telling me that my variable might not have been initialized.. I have default constructor built in the first class file, but it doesn't seem to be using it when I try accessing it through the other class...
Here is the code I just pasted it, so it kinda wrapped in some spots.
class:
public class Cat{
private String color;
private char gender;
private boolean neutered;
private String name;
private int weight;
public Cat(){
color = "orange";
gender = 'M';
neutered = true;
name = "Garfield";
weight = 20;
public void setColor(String catColor){
color = catColor;
public void setGender(char catGender){
if ((catGender == 'f') || (catGender == 'F'))
gender = 'F';
else
gender = 'M';
public void setNeutered(char catNeutered){
if ((catNeutered == 'Y') || (catNeutered == 'y'))
neutered = true;
else
neutered = false;
public void setName(String catName){
name = catName;
public void setWeight(int catWeight){
weight = catWeight;
public void weigh(){
System.out.println(name + " weighs " +
weight + "lbs.");
public void showColor(){
System.out.println(name + " is " + color);
public void eat(){
System.out.println(name + " has eaten his food
and is now full");
public void yowl(){
System.out.println(name + "yoowwwwllllll");
public void fertility(){
if (gender == 'F')
if (neutered)
System.out.println(name + "cannot have kittens.");
else
System.out.println(name + "can have kittens.");
else
if (neutered)
System.out.println(name + "cannot father kittens.");
else
System.out.println(name + "can father kittens.");
This is what I'm triing to use it with:
public class JailCats{
public static void main (String[] args) {
Cat meow1;
meow1.weigh();
}It is using the default c'tor. But since you didn't implement it, all it does is nothing.
But that's not the (immediate) problem. Somewhere you're using a local variable without setting a value for it. Hint: look at the line the error message hints at. Because I can't, because you don't tell and your posted code is unreadable.
Edit: yeah, here it is:
Cat meow1;
meow1.weigh();So where do you actually set the meow1 reference to point to a Cat instance? -
Variable mois might not have been initialized error help
String mois;
switch (month)
case 1:
mois = "January";
break;
case 2:
mois = "February";
break;
System.out.println (mois);
after compiling im getting this error.....variable mois might not have been initialized.....I don't know what it is....can somebody help???int month = keyboard.nextInt ();
if (month >= 1 && month <= 12)
else
System.out.println ("Error: invalid month. Must be in the range [1,12]");
String mois;
switch (month)
case 1:
mois = "January";
break;
case 2:
mois = "February";
break;
case 3:
mois = "March";
break;
case 4:
mois = "April";
break;
case 5:
mois = "May";
break;
case 6:
mois = "June";
break;
case 7:
mois = "July";
break;
case 8:
mois = "August";
break;
case 9:
mois = "September";
break;
case 10:
mois = "October";
break;
case 11:
mois = "November";
break;
case 12:
mois = "December";
break;
System.out.println (mois);
what is wrong with this then??? im getting the initialized error with the output of mois........ -
Error message: variable might not have been initialized
i am doing java programming and keep getting error messages: variable might not have been intitialized, the variables are 'one', 'two', and 'three' ,but at the very beginning i already had typed in String one,two,three...how do i fix this? this is part of my program:
public class Titles
public static void main(String[] args)
String book1,book2,book3,the,a,first3,first,ffirst3,ffirst,fffirst3,fffirst,one,two,three;
System.out.println("Enter the title of the first book");
book1=IO.readString();
book1=book1.trim();
System.out.println("Enter the title of the second book");
book2=IO.readString();
book2=book2.trim();
System.out.println("Enter the title of the third book");
book3=IO.readString();
book3=book3.trim();
the="the ";
a="a ";
first3=book1.substring(0,4);
ffirst3=book2.substring(0,4);
fffirst3=book3.substring(0,4);
first=book1.substring(0,2);
ffirst=book2.substring(0,2);
fffirst=book3.substring(0,2);
if (first3==the)
book1=book1.substring(4);
else
book1=book1.substring(0);
if (ffirst3==the)
book2=book2.substring(4);
else
book2=book2.substring(0);
if (fffirst3==the)
book3=book3.substring(4);
else
book3=book3.substring(0);
if (first==a)
book1=book1.substring(2);
else
book1=book1.substring(0);
if (ffirst==a)
book2=book2.substring(2);
else
book2=book2.substring(0);
if (fffirst==a)
book3=book3.substring(2);
else
book3=book3.substring(0);
int comp=book1.compareToIgnoreCase(book2);
int comp1=book1.compareToIgnoreCase(book3);
int comp2=book2.compareToIgnoreCase(book3);
if (comp<0 && comp1<0)
one=book1;
else if (comp>0 && comp1>0)
three=book1;
else
IO.reportBadInput();
if (comp2>0 && comp1<0)
two=book3;
else if (comp2<0 && comp1<0)
three=book3;
else
IO.reportBadInput();
if (comp2<0 && comp>0)
one=book2;
else if (comp2>0 && comp<0)
three=book2;
else if (comp2<0 && comp<0)
two=book2;
else
IO.reportBadInput();
if (comp1>0 && comp2>0)
one=book3;
if (comp1<0 && comp>0)
two=book1;
IO.printString(one);
IO.printString(two);
IO.printString(three);It says "not initilailized", not "not declared". The code you posted is highly unreadable, but it's likely that the compiler complains that not in every case "one" will get assigned any value.
At least do it like:
String one = null;
String two = null;
... -
Thread programming - variable might not have been initialized
Hi there,
Probably a fairly simple one here (quite new to java), i'm trying to do some thread programming but I get this error.
ThreadController.java:42: variable dataGeneratorThread might not have been initialized
dataGeneratorThread.activeCount();
The bit I dont understand is that I run
this line here
for(int i=0; i < JuliaFrame.NO_OF_DATA_GENERATORS; i++){
dataGenerators[i] = new DataGenerator(JuliaFrame.ImageWidth,JuliaFrame.ImageHeight,inputBuffer);
dataGeneratorThread = new WorkerThread(dataGenerators,juliaCalc,displayBuffer);
dataGeneratorThread.start();
but when I do
dataGeneratorThread.activeCount()
is balks.
I check that the thread is alive first but dont no how to tell the compiler this - obviously NO_OF_DATA_GENERATORS could be 0 in which case the compiler would have issues - I just wish it was more trusting ;)
Here is some of the code
runable class{
new Thread( new ThreadController(inputBuffer,displayBuffer,juliaCalc) ).start();
public class ThreadController implements Runnable {
DataBuffer inputBuffer;
DataBuffer displayBuffer;
JuliaCalc juliaCalc;
/** Creates a new instance of ThreadController */
public ThreadController(DataBuffer inputBuffer,DataBuffer displayBuffer,JuliaCalc juliaCalc) {
inputBuffer = inputBuffer;
displayBuffer = displayBuffer;
juliaCalc = juliaCalc;
public void run()
DataGenerator[] dataGenerators = new DataGenerator[JuliaFrame.NO_OF_DATA_GENERATORS];
WorkerThread dataGeneratorThread;
for(int i=0; i < JuliaFrame.NO_OF_DATA_GENERATORS; i++){
dataGenerators[i] = new DataGenerator(JuliaFrame.ImageWidth,JuliaFrame.ImageHeight,inputBuffer);
dataGeneratorThread = new WorkerThread(dataGenerators[i],juliaCalc,displayBuffer);
dataGeneratorThread.start();
dataGeneratorThread.activeCount();
int nNanoSecsBeforeCheck = 50;
while(true)
if(dataGeneratorThread.isAlive()){
if(dataGeneratorThread.activeCount() > inputBuffer.size())
public class DataGenerator implements Runnable {
int nImageWidth;
int nImageHeight;
DataBuffer inputBuffer;
public DataGenerator(int ImageWidth, int ImageHeight,DataBuffer inputBuffer) {
nImageWidth = ImageWidth;
nImageHeight = ImageHeight;
public void run()
// Non terminating thread - created datapakets and place them in the input buffer
// Get two radom number withoin a bound and find out bout default highest colou - 3rd value
while(true)
int nRandomXCord;
int nRandomYCord;
nRandomXCord = ((int)(Math.random() * nImageWidth));
nRandomYCord = ((int)(Math.random() * nImageHeight));
DataPacket dpDataPacket = new DataPacket(nRandomXCord, nRandomYCord, 233);
inputBuffer.put(dpDataPacket);Sorry about that, didnt realise.
Hi there,
Probably a fairly simple one here (quite new to java), i'm trying to do some thread programming but I get this error.
ThreadController.java:42: variable dataGeneratorThread might not have been initialized
The bit I dont understand is that I run
this line here
this line here
for(int i=0; i < JuliaFrame.NO_OF_DATA_GENERATORS; i++){
dataGenerators = new DataGenerator(JuliaFrame.ImageWidth,JuliaFrame.ImageHeight,inputBuffer);
dataGeneratorThread = new WorkerThread(dataGenerators,juliaCalc,displayBuffer);
dataGeneratorThread.start();
}but when I do
dataGeneratorThread.activeCount() is balks.
I check that the thread is alive first but dont no how to tell the compiler this - obviously NO_OF_DATA_GENERATORS could be 0 in which case the compiler would have issues - I just wish it was more trusting ;)
Here is some of the code
runable class{
new Thread( new ThreadController(inputBuffer,displayBuffer,juliaCalc) ).start();
public class ThreadController implements Runnable {
DataBuffer inputBuffer;
DataBuffer displayBuffer;
JuliaCalc juliaCalc;
/** Creates a new instance of ThreadController */
public ThreadController(DataBuffer inputBuffer,DataBuffer displayBuffer,JuliaCalc juliaCalc) {
inputBuffer = inputBuffer;
displayBuffer = displayBuffer;
juliaCalc = juliaCalc;
public void run()
DataGenerator[] dataGenerators = new DataGenerator[JuliaFrame.NO_OF_DATA_GENERATORS];
WorkerThread dataGeneratorThread;
for(int i=0; i < JuliaFrame.NO_OF_DATA_GENERATORS; i++){
dataGenerators = new DataGenerator(JuliaFrame.ImageWidth,JuliaFrame.ImageHeight,inputBuffer);
dataGeneratorThread = new WorkerThread(dataGenerators,juliaCalc,displayBuffer);
dataGeneratorThread.start();
dataGeneratorThread.activeCount();
int nNanoSecsBeforeCheck = 50;
while(true)
if(dataGeneratorThread.isAlive()){
if(dataGeneratorThread.activeCount() > inputBuffer.size())
public class DataGenerator implements Runnable {
int nImageWidth;
int nImageHeight;
DataBuffer inputBuffer;
public DataGenerator(int ImageWidth, int ImageHeight,DataBuffer inputBuffer) {
nImageWidth = ImageWidth;
nImageHeight = ImageHeight;
public void run()
// Non terminating thread - created datapakets and place them in the input buffer
// Get two radom number withoin a bound and find out bout default highest colou - 3rd value
while(true)
int nRandomXCord;
int nRandomYCord;
nRandomXCord = ((int)(Math.random() * nImageWidth));
nRandomYCord = ((int)(Math.random() * nImageHeight));
DataPacket dpDataPacket = new DataPacket(nRandomXCord, nRandomYCord, 233);
inputBuffer.put(dpDataPacket);
} -
Variable might not have been initialized Help!
Part of a servlet i am working on gets values from a select box off an html page, i am trying to use if else statement so depending what value the select a int variable is assigned a number.
if ( levelForm.equals("0"))
numRental = 3;
else if (levelForm.equals("1"))
numRental = 1;
else if (levelForm.equals("2"))
numRental = 2;
else if (levelForm.equals("3"))
numRental = 3;
String insert = "INSERT INTO customers(first_name,last_name,email,user_name,password,level, num_rentals) VALUES('" + firstNameForm + "','" + lastNameForm + "','" + emailForm + "','" + userForm + "','" + passwordForm + "','" + levelForm + "','" + numRental +"')";
System.out.println(insert);When i compile i get the an error saying numRental might not have been initialized, can anybody help me solve this?Just to expound a bit, you have:
if ( levelForm.equals("0")) //...
else if ( levelForm.equals("1")) //...
else if ( levelForm.equals("2")) //...
else if ( levelForm.equals("3")) //...What happens if levelForm.equals("4")? or "5", or null? It may be 'impossible' from your point of view, knowing how the value gets set, but the compiler can't know that and needs a default value, such as:
int numRental=3;
if ( levelForm.equals("0")) //...
else if ( levelForm.equals("1")) //...
else if ( levelForm.equals("2")) //...
else if ( levelForm.equals("3")) //...Or
if ( levelForm.equals("1")) numRental = 1;
else if ( levelForm.equals("2")) numRental = 2;
else numRental = 3;So the compiler knows that there will be exactly 3 options, and one of them will come true (if all the others fail, the last else will be executed).
ps One of the best reasons to use .equals with Strings is to prevent null pointer errors. The way you have it is backwards to protect against the null pointer. A safer method when comparing a variable of type string versus a constant string would be to put the constant String first:
if("1".equals(levelForm)) since you know the constant String can't be null. Just a pointer.
Message was edited by:
stevejluke -
Re: variable might not have been initialized
Please use code tags (simply select the code and press the code button, this will format the code nicely). You can give variables a value at declaration to keep the compiler happy; you don't actually have to use this value but Java likes to give variables a value.
variable might not have been initializedThis is a useful message from the compiler. It will always say which variable is
the problamatic one, and on which line the compiler was able to determine that
there could be a problem. (Post the full compiler message if you can't figure it out *).
Giving variables a value that you don't intend to use can "smoother" logic errors
that then don't show up until you run the program much later. I would recommend
looking at the variable in question and changing the code so that it is given the
value you intend it to have before it is used.
[Edit] * Like you did... More coffee needed... -
Variable might not have been initialized
hello all, well i'm kinda new to java, and i've been making this small game, and i've been stuck at this error since 2 days ago, please help
public void realGame1()
int qn = randomNumber.nextInt(25);
String q;
String command;
System.out.printf("%s start your battle!", p1n);
command = input.next();
if(command==q)
p2h=p2h-qn;
System.out.printf("%s's health is now %d", p2n, p2h);
That's part of the program where i'm getting the error, well i actually fixed the problem by initializing String q to null, and it worked BUT when i ran the program the System.out.printf inside the if-statement never worked, even if the user entered "q"??? can any1 help, oh and remember i'm still new, thanks in advance.q is the name of an (uninitialized) variable. I can rename the variable to foo and it would work the same way. Variable names have nothing to do with what they contain or anything at all.
Perhaps you want to test if the string command has the same contents as a specific string, like
if (command.equals("q")) -
Problem with IO objects...variable might not have been initialized?
I dont get why its wrong, i've initialized both objects and variables, i dont know why it gives me that error T__T.
Program is supposed to compare both text archives and see if they are equal in a byte per byte way.
import java.io.*;
public class TestIO
public static void main(String[] args)
throws IOException{
int i = 0, j = 0;
FileInputStream data1;
FileInputStream data2;
try{
try
data1 = new FileInputStream(args[0]);
}catch(FileNotFoundException exc){
System.out.println(args[0] + " File Not Found!");
return;
try
data2 = new FileInputStream(args[1]);
}catch(FileNotFoundException exc){
System.out.println(args[1] + " File Not Found!");
return;
}catch(ArrayIndexOutOfBoundsException exc){
System.out.println("Usage: java TestIO File1.java File2.java");
try{
do{
i = data1.read();
j = data2.read();
if(i != j) break;
}while(i != -1 && j != -1);
}catch(IOException exc){
System.out.println("File Error!");
if (i != j)
System.out.println("Files Differ");
else
System.out.println("Files are the same");
data1.close();
data2.close();
}Help is appreciated, thanks in advance ^____^ .import java.io.*;
public class FileDiff {
public static boolean diff(File file1, File file2) throws IOException {
BufferedInputStream in1 = new BufferedInputStream(new FileInputStream(file1));
try {
return diff(in1, file2);
} finally {
in1.close();
public static boolean diff(InputStream in1, File file2) throws IOException {
BufferedInputStream in2 = new BufferedInputStream(new FileInputStream(file2));
try {
return diff(in1, in2);
} finally {
in1.close();
public static boolean diff(InputStream in1, InputStream in2) throws IOException {
int b1, b2;
while ((b1 = in1.read()) != -1 & (b2 = in2.read()) != -1 ) {
if (b1 != b2)
return true;
return b1 != b2;
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Usage: java FileDiff file1 file2");
} else {
try {
System.out.println(diff(new File(args[0]), new File(args[1])));
} catch(IOException e) {
System.out.println(e.getMessage());
} -
Variable j might not have been initialized
import java.io.*;
import java.util.*;
class Multiply
public static void main(String args[]) throws IOException
int i=1,j;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter a number:");
int n = Integer.parseInt(br.readLine());
if(j==i*n && i<=20)
System.out.println(" the multiply table is:" +j);
i++;
i ompile this program but this gives an error i.e.,
variable j might not have been initialized
if(j==i*n && i<=20)
what's my mistake i couldn't understand
pls help me> what's my mistake i couldn't understand
You initialized 'i', but not 'j'. You try to access 'j' before it has been initialized. The compiler is telling you that such a thing is against the rules.
~ -
Variable strShow might not have been initialized
<%
String strShow,strFigure;
for (int i=0;i<100;i++)
strFigure=Integer.toString(i); // does it really not be initialized ?
strShow+=strFigure; // strShow can't automatically wisely assign memory space for itself ?
%>
the errors messages:
variable strShow might not have been initialized
strShow+=strFigure;
variable strFigure might not have been initialized
strShow+=strFigure;the codes should be remedied like this :
<%
String strShow=new String();
String strFigure=new String();
for (int i=0;i<100;i++)
strFigure=Integer.toString(i);
strShow+=strFigure;
out.println(strShow);
%>
now I have a further comprehension about String object,thanks! -
Variable myConnection might not have been initialized
I'm getting a strange exception I don't understand. Can anyone help me out?
"variable myConnection might not have been initialized"
DataSource dataSource;
Connection myConnection;
ResultSet rs;
Statement pStmt;
try {
dataSource = getDataSource(request);;
myConnection = dataSource.getConnection();
// does stuff with connection
} catch (SQLException sqle) {
getServlet().log("Connection.process", sqle);
} finally {
try {
myConnection.close();
} catch (SQLException e) {
getServlet().log("Connection.close", e);
}Is there any way to force compliation of my code with
this error?What??? An error is an error is an error. Just simply assign it to null beforehand, like you should do. -
Might not have been initialized
I've seen this posted in here before and i've gone through a search but still can't figure out what i've done wrong.
Here are the error's:
A:\Chapter04\Tuition.java:101: variable tuition might not have been initialized
total = tuition + fees;
^
A:\Chapter04\Tuition.java:101: variable fees might not have been initialized
total = tuition + fees;
^
2 errors
Tool completed with exit code 1
Here is the code:
public static void displayTotal(double total)
double tuition, fees;
total = tuition + fees;
DecimalFormat twoDigits = new DecimalFormat("$#000.00");
System.out.println("Your cost for tuition is; " + twoDigits.format(total));
when I change ' double tuition, fees' to ' double tution = 0, fees =0; '
it compiles fine but when run it does not return the right values, i'm sure its something silly like the last.
Thanks again for your wisdom and patiencewhen I change ' double tuition, fees' to ' double
tution = 0, fees =0; '
it compiles fine but when run it does not return the
right values, i'm sure its something silly like the
last.So you set the tuition and fees to zero, added them to
the value passed in, and expected to come up with
something other than the original value? You need to
get the right values for tuition and fees somehow. I
have no idea how since I don't know anything about
your application.I'm srry here is all the code:
import java.io.*;
import java.text.DecimalFormat;
public class Tuition
public static void main(String[] args) throws IOException
//Declare variables
int hours;
double fees , rate, tuition;
//Call methods
displayWelcome();
hours = getHours();
rate = getRate(hours);
tuition = calcTuition(hours, rate);
fees = calcFees(tuition);
displayTotal(tuition + fees);
public static void displayWelcome()
System.out.println("Welcome to the Tuition Calculator");
System.out.println();
public static int getHours() throws IOException
//Declare variables
BufferedReader dataIn = new BufferedReader ( new InputStreamReader(System.in));
String strHours;
int hours;
hours = 0;
// Get value from user
System.out.println("Enter the total amount of Credit hours to be taken:");
strHours = dataIn.readLine();
try
hours = Integer.parseInt(strHours);
catch(NumberFormatException errNum)
System.out.println("Your entry was not in the proper format." + errNum.getMessage());//message prints with Java-generated data
//Return a value to main
return hours;
public static double getRate(int hours)
//Declare variables
double rate;
boolean done = false;
if (hours > 15)
rate = (44.50);
else
rate = (50.00);
//Return a value to main
return rate;
public static double calcTuition(int hours, double rate)
//Declare variables
double tuition;
tuition=0;
tuition = hours * rate;
//Return a value to main
return tuition;
public static double calcFees(double tuition)
//Declare variables
double fees;
fees = tuition*.08;
// Return a value to main
return fees;
public static void displayTotal(double total)
total = (double)tuition + (double)fees;
DecimalFormat twoDigits = new DecimalFormat("$#000.00");
System.out.println("Your cost for tuition is; " + twoDigits.format(total)); -
Pls Help! InetAddress: might not have been initialized
variable inetAddr might not have been initialized
InetAddress inetAddr = inetAddr.getByName(someClass.sInetAddr);
where someClass.sInetAddr.equals("xxx . xxx . xxx . xxx")
Please if you know help me.
Thank you in advanceLook at the other thread, you are trying to use the which you have yet to set variable instead of the class name to invoke getByName(). It should be:
InetAddress inetAddr = InetAddress.getByName(someClass.sInetAddr);
Chuck
Maybe you are looking for
-
Nokia 920 Bluetooth and SMS Speech
I have a Nokia 920 and I recently changed from a Toyota RAV4 to a VW Golf 2013 MK7 TSI 90 Comfortline in Australia on Telstra. Previously, when paired with my RAV4 whenever I got incoming SMS text it would announce text from the phone contact and off
-
I had this problem on previous versions of FF and thought the upgrade would help, but it didn't.
-
Hi All, I am newbie, I have one question. suppose there is One table containing hundreds of records and now i have added DATE column in that table and Now I have to insert the sysdate in that column for all rows. Then how can i do it by executing a s
-
I was wondering is it possible to have a page with a single photo which after a time delay, dissolves/cycles to the next? thanks
-
Landed Cost - BK Profit Center error
Hello, I am trying to add a landed cost document in the system but it is giving an error that I ''BK-Please enter profit center" I have been using this for a year now and I dont put any profit center. what could have caused this?? PO was raised in J