user2650063
user2650063

Reputation:

how to override variabe value in java in if else statement

Hey Guys , Simple code .i newly enter in java i want to show input message again in else statement and override num1 variable .but message which i face "duplicate local variable string a and num1".Please suggest best solution. Here is my code

String a =JOptionPane.showInputDialog("Please enter  the first Number :");      
int num1=Integer.parseInt(a);
int con1=JOptionPane.showConfirmDialog(null,num1);
if(con1==JOptionPane.YES_OPTION)
 {
JOptionPane.showMessageDialog(null,num1);
}
else{

String a=JOptionPane.showInputDialog("Pleaee enter  the first Number :");   
int num1=Integer.parseInt(w);

}

Upvotes: 0

Views: 873

Answers (2)

Haseeb Anser
Haseeb Anser

Reputation: 504

As {if/else} is conditional statement so you can't add duplicate values with same variable names.so you can try removing the duplicate declarations as below:

String a =JOptionPane.showInputDialog("Please enter  the first Number :");      
int num1=Integer.parseInt(a);
int con1=JOptionPane.showConfirmDialog(null,num1);
if(con1==JOptionPane.YES_OPTION)
 {
JOptionPane.showMessageDialog(null,num1);
}
else{

 a=JOptionPane.showInputDialog("Pleaee enter  the first Number :");   
 num1=Integer.parseInt(w);

}

Upvotes: 1

farhan patel
farhan patel

Reputation: 1610

you're declaring variable 'a' and num1 twice in your code, you can either create variable with some different name or try below code to fix the error.

String a =JOptionPane.showInputDialog("Please enter  the first Number :");      
int num1=Integer.parseInt(a);
int con1=JOptionPane.showConfirmDialog(null,num1);
  if(con1==JOptionPane.YES_OPTION)
   {
    JOptionPane.showMessageDialog(null,num1);
   }
  else{

    a=JOptionPane.showInputDialog("Pleaee enter  the first Number :");   
    num1=Integer.parseInt(w);
  }

Upvotes: 1

Related Questions