Variable not initialized JAVA error

Discussion in 'Software' started by slashgonewylde, Oct 20, 2009.

  1. slashgonewylde

    slashgonewylde Private E-2

    This is my code:

    import java.text.DecimalFormat;
    import javax.swing.JOptionPane;

    public class Printing

    {

    public static void main(String[]args)

    {

    int c;
    double total;

    String input;

    DecimalFormat dfmt = new DecimalFormat("#0.00");

    input = JOptionPane.showInputDialog("How many copies do you want to make? ");
    c = Integer.parseInt(input);

    c = 1111; //false number

    if (c > 0 && c <= 99) {
    System.out.println("Total = " + dfmt.format(total));
    }

    total = 0.30*c;

    }

    }


    //the error is


    java:25: variable total might not have been initialized
    System.out.println("Total = " + dfmt.format(total));
    ^
    1 error


    Thanks matt
     
  2. JJJIrish05

    JJJIrish05 Sergeant

    Change 'double total;' to 'double total=0.0;'
     
  3. slashgonewylde

    slashgonewylde Private E-2

    This took away the error but the if statement did not work. What exactly did that change do to the code?
     
  4. JJJIrish05

    JJJIrish05 Sergeant

    It really changed essentially nothing, just made java happy.

    Since you're doing "c = 1111; //false number", the if statement wont be true since 1111 isn't between 0 and 99.

    Also did you mean to set "total = 0.30*c;" AFTER the if statement? Or did you want to do that before the if statement?
     
  5. slashgonewylde

    slashgonewylde Private E-2

    No that was my mistake. Thanks for the help.
     
  6. JJJIrish05

    JJJIrish05 Sergeant

    You're welcome.
     

MajorGeeks.Com Menu

Downloads All In One Tweaks \ Android \ Anti-Malware \ Anti-Virus \ Appearance \ Backup \ Browsers \ CD\DVD\Blu-Ray \ Covert Ops \ Drive Utilities \ Drivers \ Graphics \ Internet Tools \ Multimedia \ Networking \ Office Tools \ PC Games \ System Tools \ Mac/Apple/Ipad Downloads

Other News: Top Downloads \ News (Tech) \ Off Base (Other Websites News) \ Way Off Base (Offbeat Stories and Pics)

Social: Facebook \ YouTube \ Twitter \ Tumblr \ Pintrest \ RSS Feeds