简体   繁体   English

将数值变量从HTML传递到Java

[英]Passing numeric variable from HTML to java

This is my java class and I got NumberFormatException . 这是我的java类,并且得到NumberFormatException Can anyone help me? 谁能帮我? I have tried many times but it keeps having that error. 我已经尝试过很多次了,但是它始终会出现该错误。

public class HelloFromHTML extends JApplet
{

    String name;
    String age, dimensions1 ,dimensions2;
    int num;
    Font f;

    public void init()
    {   
        f = new Font("TimesRoman", Font.BOLD,30);

        String a = this.getParameter("ageHTML");
        num = Integer.parseInt(a);      

        name = "Hello " + getParameter("nameHTML") + " " + num + " years'"; 
        dimensions1 = "JApplet size is " + getParameter("width") + ", " +  getParameter("height");  
        dimensions2 = "size is " + String.valueOf(getWidth()) + ", " +  String.valueOf(getHeight());
    }

    public void paint(Graphics g)
    {
        super.paint(g);

        g.setFont(f);
        g.setColor(Color.black);

        //////////////////////////////////
        //   Display String
        g.drawString(name,5,50);
        g.drawString(dimensions1,5,100);
        g.drawString(dimensions2,5,200);
    }
}

Since the line num = Integer.parseInt(a); 由于行num = Integer.parseInt(a); causes that Exception to be thrown, i advice you to surround it with a try-catch block. 导致抛出该Exception ,我建议您用try-catch块将其包围。 And also, debug your code to see why a is not a number. 另外,调试代码以查看为什么a不是数字。 It is a good practice to catch any Exception that may be thrown. catch可能引发的任何Exception是一个好习惯。

try{
    num = Integer.parseInt(a);
}
catch(NumberFormatException e){
   //TODO: what happens when "a" is not a number
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM