Error with initializing in JAVA

Discussion in 'Software' started by slashgonewylde, Nov 4, 2009.

  1. slashgonewylde

    slashgonewylde Private E-2

    This is my code:


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

    public class MathTutor

    {

    public static void main(String[]args)

    {

    int num1;
    int num2;
    int sum;
    int answer;
    int symbol;

    String input;

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

    Random r = new Random();

    num1 = r.nextInt(10)+ 1;
    num2 = r.nextInt(10)+ 1;
    symbol = r.nextInt(4)+ 1;

    if (symbol == 1){
    sum = num1 + num2;
    }
    if (symbol == 2){
    sum = num1 - num2;
    }
    if (symbol == 3){
    sum = num1*num2;
    }
    if (symbol == 4){
    sum = num1/num2;
    }

    input = JOptionPane.showInputDialog(null, "What is the answer to the following question? \n" + num1 + symbol + num2 + " = ?");
    answer = Integer.parseInt(input);

    if (answer == sum){
    JOptionPane.showMessageDialog(null, "Correct!");
    }
    else{
    JOptionPane.showMessageDialog(null, "Wrong! The answer is: " + sum);
    }

    }





    This is the error:


    java:45: variable sum might not have been initialized
    if (answer == sum){
    ^
     
  2. JJJIrish05

    JJJIrish05 Sergeant

    just change 'int sum;' to 'int sum=0;'

    since the only time you give sum a value is inside of an if statement, java assume the worst that none of your if statements are true, therefore will never be initiazlied

    welcome to java :p
     
  3. slashgonewylde

    slashgonewylde Private E-2

    haha thanks
     

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