java如何在下面的程序中消除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 楼答案
只需在
try-catch
块中进行如下更改