使用 BufferedReader 的 readline() 输入 arraylist
input for arraylist using readline() of BufferedReader
我正在尝试使用 BufferedReader 获取输入并将它们添加到数组列表中。
该代码正在接受无穷无尽的输入,并且不会前进到更多行(不退出 for 循环)。
请找到我的以下代码:
public class ALinput {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n2 = br.read();// number of items in the list
ArrayList<String> list2 = new ArrayList<String>();
for(int i =1;i<=n2;++i)
{
list2.add(br.readLine());
}
System.out.println(list2);//printing list before sorting
Collections.sort(list2);//sorting the list
System.out.println("After sorting "+list2);
}
}
我将 n2 作为数组列表中元素的数量。
如果输入 n2 = 5;
在将 5 个字符串添加到 arraylist 后,readLine 继续无休止地进行文本输入而不会退出。
它不是从 for 循环中出来的。请帮助我理解我在这里犯的错误。
其实不是永远的,零的字符代码是48,一是49,二是50,依此类推。所以当你输入 5 时,计算机读取它的字符值,并将 n2 存储为 53,让你输入 52 个输入。为什么是 52 而不是 53?
还有第二个错误,br.read()
只查看输入的第一个字节,所以一个字符。第一次调用 br.readLine()
时,它会完成读取您键入的第一个数字后行中的内容。要解决这些问题,只需更改
int n2 = br.read();
到
int n2 = Integer.parseInt(br.readLine());
瞧!完毕!
P.S。您可能希望将 Integer.parseInt()
包围在 try catch 块中,以防用户输入数字以外的内容。
我正在尝试使用 BufferedReader 获取输入并将它们添加到数组列表中。 该代码正在接受无穷无尽的输入,并且不会前进到更多行(不退出 for 循环)。 请找到我的以下代码:
public class ALinput {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n2 = br.read();// number of items in the list
ArrayList<String> list2 = new ArrayList<String>();
for(int i =1;i<=n2;++i)
{
list2.add(br.readLine());
}
System.out.println(list2);//printing list before sorting
Collections.sort(list2);//sorting the list
System.out.println("After sorting "+list2);
}
}
我将 n2 作为数组列表中元素的数量。 如果输入 n2 = 5; 在将 5 个字符串添加到 arraylist 后,readLine 继续无休止地进行文本输入而不会退出。 它不是从 for 循环中出来的。请帮助我理解我在这里犯的错误。
其实不是永远的,零的字符代码是48,一是49,二是50,依此类推。所以当你输入 5 时,计算机读取它的字符值,并将 n2 存储为 53,让你输入 52 个输入。为什么是 52 而不是 53?
还有第二个错误,br.read()
只查看输入的第一个字节,所以一个字符。第一次调用 br.readLine()
时,它会完成读取您键入的第一个数字后行中的内容。要解决这些问题,只需更改
int n2 = br.read();
到
int n2 = Integer.parseInt(br.readLine());
瞧!完毕!
P.S。您可能希望将 Integer.parseInt()
包围在 try catch 块中,以防用户输入数字以外的内容。