我是个初学者,向问一下对于java语言如何进行数组分配
我准备做一个成绩统计的程序,但是不知道班里多少人,也就是说班里的人数需要输入一下
System.out.println("请输入该班级的人数");
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
int n=Integer.parseInt(s);
}
catch(Exception e)
{System.err.println("数据格式化错误:"+e);}
但是我要是用数组的话
int a[]=new int[n];
这样是错误的,和c、c++是一样的:
要是c,我可以用结构体做一个链表,那么用java怎么弄呢 ??
我准备做一个成绩统计的程序,但是不知道班里多少人,也就是说班里的人数需要输入一下
System.out.println("请输入该班级的人数");
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
int n=Integer.parseInt(s);
}
catch(Exception e)
{System.err.println("数据格式化错误:"+e);}
但是我要是用数组的话
int a[]=new int[n];
这样是错误的,和c、c++是一样的:
要是c,我可以用结构体做一个链表,那么用java怎么弄呢 ??
import java.io.BufferedReader;
import java.io.InputStreamReader;public class Test
{
public static void main(String[] args)
{
int n = 0;
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
n=Integer.parseInt(s);
}
catch(Exception e)
{
System.out.println("number format error!!");
}
int[] a = new int[n];
for(int i = 0; i < a.length; i++)
a[i] = i;
for(int j = 0; j < a.length; j++)
System.out.println(a[j]);
}
}
这样是错误的,和c、c++是一样的:------------------------------------
即使在c ,C++里面这样也是可以的啊
只要n初始化了
你的n在try里面声明 是个局域变量