I am running a simple applet in my machine.Note that when executing applet "Number format exception" error occurs when the applet is trying to run. The below code is shown
import java.util.*;
import java.awt.*;
import java.applet.*;
<html>
<body>
<applet code="s09_03.class" width=400 height=400>
</applet>
</body>
</html>
public class s09_03 extends Applet
{
GregorianCalendar cal=new GregorianCalendar();
String s,s1,s2,s3,s4;
int a=0,b=0,c=0,d=0;
public void start(){s=getParameter("fg");
s1=getParameter("as");
s2=getParameter("as1");
s3=getParameter("as2");
s4=getParameter("as3");
a=Integer.parseInt(s1);
b=Integer.parseInt(s2);
c=Integer.parseInt(s3);
d=Integer.parseInt(s4);
}
public void init()
{
}
public void paint(Graphics g)
{
if(s.equals("red"))g.setColor(Color.red);g.drawRect(a,b,c,d);
g.drawString("Color = "+"",25,25);
g.drawString("Calendar is"+cal.DATE+"/"+cal.MONTH+"/"+cal.YEAR,34,36);
}
}
The command used are
javac s09_03.java
and
appletviewer s09_03.java
Terminal output:
java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:443)
at java.lang.Integer.parseInt(Integer.java:514)
at s09_03.start(s09_03.java:22)
at sun.applet.AppletPanel.run(AppletPanel.java:477)
at java.lang.Thread.run(Thread.java:701).
So my question is why this error occurs and when does it usually occur??Also suggest some necessary changes in code so that the code runs without any error.Note that the code is being run through linux...Thanks...
~
Take a look Try-Catch , NumberFormatException , nullPointerException
Use try catch
to handle the Exception
Try this, because you got the value as null
. so check the passing value should not be null
try
{
a = Integer.parseInt(s1 != null ? s1 : "0");
b = Integer.parseInt(s2 != null ? s2 : "0");
c = Integer.parseInt(s3 != null ? s3 : "0");
d = Integer.parseInt(s4 != null ? s4 : "0");
}
catch(NumberFormatException ex)
{
System.out.println("Exception : "+ex);
}
And also the variable s is also null
so you got the NullPointerException
if (s != null && s.equals("red"))
instead of
if (s.equals("red"))
Catch the Exception and handle it
try{
a=Integer.parseInt(s1);
b=Integer.parseInt(s2);
c=Integer.parseInt(s3);
d=Integer.parseInt(s4);
} catch(NumberFormatException e){
//exceptionhandling
}
Simply catch the exception in catch block and take the appropriate action.
try{
// some code that may throw NumberFormatException
}catch(NumberFormatException e){
// when number format exception occur, take appropriate action
}
Root cause of your problem:
As exception says clearly
java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:443)
You are trying to parse a String value that is null into an Integer, that is why parseInt() threw an exception.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.