Search code examples
javaarraystry-catchnumberformatexception

How to get rid of NumberFormatException in the following program?


A program to accept an array of integers and another array of symbols and to *calculate and display the result after performing the operations using the *symbols. example:

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

This is what I did.

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);
    }
    }

How can I get the answer using try catch instead of getting zero or is there another method to do the same program?


Solution

  • Just do some changes as like below in your try-catch block

    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);
    }