[英]how to accept string array in java using bufferedreader
public static void accept_name( String[] name, int[] r)
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader ab = new BufferedReader(isr);
r = new int[40];
name = new String[40];
for(int i=0;i<40;i++)
{
System.out.println("Enter the name of students");
name[i] = ab.readLine();
}
}
我在名字[i] = ab.readLine();
我不明白这是什么问题。
实际上,如果你鼠标悬停在错误行上,那里的消息就会告诉你一切。
这是一个编译时错误。请求exception
处理。执行该行时有机会获得IOException
。
所以你必须通过抛出method
签名或自己捕获它来handle
它。
将您的方法更改为
public static void accept_name( String[] name, int[] r)
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader ab = new BufferedReader(isr);
r = new int[40];
name = new String[40];
for(int i=0;i<40;i++)
{
System.out.println("Enter the name of students");
try {
name[i] = ab.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
您在函数参数中获取名称数组为什么要再次初始化它? 以下不是必需的
name = new String[40];
r = new int[40];
你的代码必须是
public static void accept_name( String[] name, int[] r)
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader ab = new BufferedReader(isr);
for(int i=0;i<40;i++)
{
System.out.println("Enter the name of students");
try {
name[i] = ab.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
然后你可以把你的功能称为
String[] name = new String[40];
//populate your name array
int[] r = new int[40];
//populate your r array
ClassName.accept_name(name,r);//Static function
我也看不到你在哪里使用r。
Readline会抛出IOException,因此您应该捕获它或重新抛出。
public static void accept_name(String[] name, int[] r) throws IOException {
[...]
}
卡罗
使用Input \\ Output流时,需要IOException
,定义它可能抛出这种异常:
public static void accept_name (String[] name, int[] r) throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader ab = new BufferedReader(isr);
r = new int[40];
name = new String[40];
for(int i=0;i<40;i++)
{
System.out.println("Enter the name of students");
name[i] = ab.readLine();
}
}
你可以尝试这个......
public static void accept_name( String[] name, int[] r)
{
name = new String[40];
for(int i=0;i<40;i++)
{
try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader ab = new BufferedReader(isr);
System.out.println("Enter the name of students");
name[i] = ab.readLine();
ab.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.