[英]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.