• Post Reply Bookmark Topic Watch Topic
  • New Topic

Error  RSS feed

 
Ambika Kumar
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hai...

I have got an error after compiling a simple try... catch program

Code is:

import javax.swing.*;
public class amma1
{
public static void main(String args[])
{
int i,n;
try
{
n=Integer.parseInt(JOptionPane.showInputDialog("Enter no:"));
}
catch(Exception e)
{
System.out.println("Number not entered");
}

String name=JOptionPane.showInputDialog("Enter your name:");

for(i=0;i<n;i++)
{
System.out.println(name);
}
}
}

Error is: variable n might not have been initialized
 
Craig Tyler
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since you assign a value to n in the try block, an exception (in this case a NumberFormatException) might get thrown before you actually assign the value to n. If that happens, when you want to use n, it would still be uninitialized. To avoid this, assign a default value to n (like 0) when you declare it. That way, even if you do get an exception that prevents n being assigned to anything, you still have a valid value in n.
[ February 13, 2006: Message edited by: Craig Tyler ]
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, think about the code flow. I the user misentered a number what do you want to do -- go on and ask them for their name? Probably not. I think you might want to give them a chance to enter the number again.
 
Tony Ben
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi mr.Ambika kumar
create a variable as globally that u can access the variable in any where plz try this program which i have send ok .



import javax.swing.*;

public class aama1
{
public static void main(String args[])
{
int i,n;
try
{

n=Integer.parseInt(JOptionPane.showInputDialog("Enter no:"));

System.out.println("Number not entered");

String name=JOptionPane.showInputDialog("Enter your name:");

for(i=0;i<n;i++)
{
System.out.println(name);
}
}
catch(Exception e)
{
System.out.println(e);
}
System.exit(0);
}

}


try this ok bye......
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!