Variable might not have been initialised?

Hi I declare 2 lists at the begining of a method, the is "wrapped" using the Collections.synchronizedList method but when I try to compile the application it gives me the errors variable alltitles might not have been initialised and variable allauthors might not have been initialised: Here is my code
List allauthors = Collections.synchronizedList(new ArrayList(allauthors));
      List alltitles = Collections.synchronizedList(new ArrayList(alltitles));//The next statements are inside a loop
alltitles.add(TITLE);
            allauthors.add(names);I cannot figure out how to initialise the list at the begining of the method?
is this the problem please help

I'll give you a hint on how to default-initialize any object so that the compiler stops bothering you :
x = null;hope this helps ;-)

Similar Messages

  • Variable data might  not have been initialised &

    Object [][] data; //WARNING variable data is not used
                        while(s.getResultSet().next()) {
                                data[0] = s.getResultSet().getDate(2); // ERROR variable data might not have been initialised
    data[i][1] = s.getResultSet().getString(1);
    data[i][2] = s.getResultSet().getString(7);
    System.out.println(i++);
    final JTable table = new JTable(data, columnNames); // ERROR variable data might not have been initialised
    Hi All,
    I am trying to load some items from my database server into my Object array and then pass the Object array into my JTable to be displayed.  The problem is when I put the data[0]... within my while loop I get compilation errors starting that the variable might not have been inititialised.
    So I then intialise my array but when I do that I get this Error: ERROR java.lang.ArrayIndexOutOfBoundsException: 1.
    Any ideas how I can get it to load my data properly?

    Note: please post responses to either of #1 or #2, attempting to reply to the OP will fail with a server error.
    db
    Edited by: DarrylBurke
    Question already answered in [http://forums.sun.com/thread.jspa?threadID=5412500]

  • 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?

  • 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...

  • 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

  • To DaveyB re: variable data might not have been initialised

    I tried to reply to your thread but got a server error. It's not happening for other threads, and I don't know if others are experiencing the same problem.
    If you don't get a response within the next hour, try posting again, or just reply here.
    In the meantime, your problem is this:
    int[] x;
    x[0] = 1; // ERROR
    int[] y = new int[10];
    y[0] = 1;You didn't give the array variable x a value.

    I am very sorry and thank you very much for anwering...
    I was waiting for an email to drop into my inbox stating my my message had an answer, strange that you can't reply to my thread.
    Here is the modified version
                        Object [][] data = {{this.now(), "test", "test"}};
                        while(s.getResultSet().next()) {
                                data[0] = s.getResultSet().getDate(2);
    data[i][1] = s.getResultSet().getString(1);
    data[i][2] = s.getResultSet().getString(7);
    System.out.println(i++);
    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    When this is ran I get the below error, I specified this before but didn't give an example.  I hope the example helps.run:
    0
    ERROR java.lang.ArrayIndexOutOfBoundsException: 1
    Java2D Direct3D usage disabled by J2D_D3D env
    BUILD SUCCESSFUL (total time: 59 seconds)

  • 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".

  • 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 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........

Maybe you are looking for

  • Burning not allowed in iDVD, Size is the problem?

    Im workin on my iMac iCore 5 with iDVD 7.1.2 and Leopard OS 10.6.8. Try to finish a project with two .mp4 files below 3.05 Gb but when I try to burn it out, it tells me Im exceding the maximum size to work with. Im using 4.7 DVD R discs. What is the

  • MacMini 2012 with multiple monitors?

    Hi folks, I have a Mac Mini 2012 and I'm currently using a Panasonic 720p TV as a monitor via the HDMI port. I've purchsed a HDMI splitter as I want to run a second smaller monitor simultaeneously. Can I use the HDMI to DVI adaptor and run a DVI Moni

  • Login shows up twice?

    I have noticed that for the last week or so, everytime I lift open the lid, my Powerbook wakes up from its sleep and asks me my password. I type it in and press enter, my screen goes blank, and then the login shows up again. The second time around it

  • SCEP 2012 System Center Monitoring Pack for Linux v4.5.10.1 Problem

    Hi Everyone! We are having a problem with OpsMgr 2012 R2 and the System Center Monitoring Pack for SCEP 2012 for Linux v4.5.10.1.  We have successfully deployed the Linux OpsMgr 2012 R2 agent to our test CentOS 6.5 VM as well as SCEP 2012 v4.5.10.1. 

  • How to deactivate current phone and activate a dif. One?

    My phone is messing up so I'm wanting to turn it off and use a different phone for that line. How do I do this?