【问题标题】:how to accept string array in java using bufferedreader如何使用bufferedreader在java中接受字符串数组
【发布时间】:2013-05-28 00:04:40
【问题描述】:
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();
我不明白问题出在哪里。
【问题讨论】:
标签:
java
arrays
string
bufferedreader
【解决方案1】:
实际上,如果您将鼠标悬停在错误行上,那里的消息就会说明一切。
这是一个编译时错误。请求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();
}
}
}
Heavily recommending concept
【解决方案2】:
您在函数参数中获取名称数组为什么要再次初始化它?
以下不是必须的
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。
【解决方案3】:
Readline 抛出一个 IOException,因此您应该捕获它或重新抛出它。
public static void accept_name(String[] name, int[] r) throws IOException {
[...]
}
卡洛
【解决方案4】:
当使用 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();
}
}
【解决方案5】:
你可以试试这个……
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();
}
}
}