java中数组的运行时初始化
我无法理解为什么我在初始化main中的数组时出错。我清除了一个变量t,并从键盘上获取它的值。但是,当我尝试初始化大小为t的数组n[]时,它会显示一个错误。plz helpjava中数组的运行时初始化,java,arrays,Java,Arrays,我无法理解为什么我在初始化main中的数组时出错。我清除了一个变量t,并从键盘上获取它的值。但是,当我尝试初始化大小为t的数组n[]时,它会显示一个错误。plz help import java.io.*; import java.math.BigInteger; class smallfac { static BigInteger fac(BigInteger x) { BigInteger z; if(x.equals(new BigInte
import java.io.*;
import java.math.BigInteger;
class smallfac
{
static BigInteger fac(BigInteger x)
{
BigInteger z;
if(x.equals(new BigInteger("1")))
return x;
else
{
z=x.multiply(fac(x.subtract(new BigInteger("1"))));
return(z);
}
}
public static void main(String args[])
{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
try{
int t=Integer.parseInt(br.readLine());
}catch(IOException e){}
int[] n=new int[t];
for(int i=0;i<n.length;i++)
{
try
{
n[i]=Integer.parseInt(br.readLine());
}catch(IOException e){}
}
for(int i=0;i<n.length;i++)
{
int x=n[i];
BigInteger p = new BigInteger(Integer.toString(x));
p=smallfac.fac(p);
System.out.println(p);
}
}
}
import java.io.*;
导入java.math.biginger;
smallfac类
{
静态BigInteger fac(BigInteger x)
{
大整数z;
if(x.equals(新的大整数(“1”))
返回x;
其他的
{
z=x.multiply(fac(x.subtract)(新的大整数(“1”)));
返回(z);
}
}
公共静态void main(字符串参数[])
{
InputStreamReader in=新的InputStreamReader(System.in);
BufferedReader br=新的BufferedReader(in);
试一试{
int t=Integer.parseInt(br.readLine());
}捕获(IOE){}
int[]n=新的int[t];
对于(int i=0;iint[]n=new int[t];
这是一个范围问题。您在try
块内声明int t
,但随后尝试在其后面使用t
的值,这是不可能的;t
仅在try
块内可见,我看到一些问题:
try{
int t=Integer.parseInt(br.readLine());
}catch(IOException e){}
int[] n=new int[t];
有两个问题:
t
仅在try
块内声明。它超出了该块的范围。因此,试图在上面最后一行使用t
时出现编译时错误
即使您通过在块外声明t
然后在块内初始化它来修复此问题,编译器也无法确保t
具有上面最后一行的值。可能会引发异常。因此这是一个错误(编译时错误)
后者是第三个问题(至少):
t
是在try block内部定义的。因此,它的范围仅限于try block
。您不能在try block外部访问它。请在try外部定义它,以便您的数组初始化可以访问它。几个问题之一。:-t
必须存在,但不需要是常量。
try{
int t=Integer.parseInt(br.readLine());
}catch(IOException e){}
int[] n=new int[t];
for(int i=0;i<n.length;i++)
{
try
{
n[i]=Integer.parseInt(br.readLine());
}catch(IOException e){}
}
public static void main(String args[])
{
// Put all the code in one try block
try {
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
int t=Integer.parseInt(br.readLine());
int[] n=new int[t];
for(int i=0;i<n.length;i++)
{
n[i]=Integer.parseInt(br.readLine());
}
for(int i=0;i<n.length;i++)
{
int x=n[i];
BigInteger p = new BigInteger(Integer.toString(x));
p=smallfac.fac(p);
System.out.println(p);
}
}catch(IOException e){
// Report the error here
}
}