如何摆脱以下程序中的NumberFormatException?

时间:2018-03-22 04:41:06

标签: java arrays try-catch numberformatexception

一个程序,用于接受整数数组和另一个符号数组,并在使用*符号执行操作后计算并显示结果。例如:

int Arr[]={1,2,3,4} 
String Sym[]={"+","/","*"}
Result is 4. *[((1+2)/3)*4]

这就是我所做的。

import java.util.*;
public class Array
{
public static void main(String args[])
{
    Scanner sc=new Scanner(System.in);int c=0;
    System.out.println("Enter the size of the array:");
    int l=sc.nextInt();
    int m[]=new int[l];
    String n[]=new String[l-1];
    String s[]=new String[l];
    System.out.println("Enter the integers");
    for(int i=0;i<l;i++)
    {
        m[i]=sc.nextInt();
        s[i]=Integer.toString(m[i]);
    }
    System.out.println("Enter the symbols");
    for(int i=0;i<l-1;i++)
    {
        n[i]=sc.next();
    }
    String st="";
    for(int i=0;i<l;i++)
    {
        if(i<(l-1))
         st=st+s[i]+n[i];
         else
         st=st+s[i];
    }

    System.out.println("String looks like "+st);
    try
    {
      c=Integer.parseInt(st);
    }
    catch(NumberFormatException ex)
    {}
    System.out.println("Answer "+c);
    }
    }

如何使用try catch获得答案而不是获得零 还是有另一种方法来做同样的程序?

1 个答案:

答案 0 :(得分:0)

只需在try-catch

中进行如下所示的更改
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int c = 0;
    System.out.println("Enter the size of the array:");
    int l = sc.nextInt();
    int m[] = new int[l];
    String n[] = new String[l - 1];
    String s[] = new String[l];
    System.out.println("Enter the integers");
    for (int i = 0; i < l; i++) {
        m[i] = sc.nextInt();
        s[i] = Integer.toString(m[i]);
    }
    System.out.println("Enter the symbols");
    for (int i = 0; i < l - 1; i++) {
        n[i] = sc.next();
    }
    String st = "";
    for (int i = 0; i < l; i++) {
        if (i < (l - 1))
            st = st + s[i] + n[i];
        else
            st = st + s[i];
    }

    System.out.println("String looks like " + st);
    try {

        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");
        c = (int) engine.eval(st);
    } catch (NumberFormatException ex) {
        ex.printStackTrace();
    } catch (ScriptException e) {
        e.printStackTrace();
    }
    System.out.println("Answer " + c);
}