我正在编写一个程序,我必须读取大约 10^6 个整数。 我尝试使用扫描仪类,但是当我尝试 800000*3 输入时,大约需要 12.38 秒。 我还尝试使用 BufferedReader,它实际上工作得更快,但它不会接受我按需要提供的输入。
For e.g. if I want to read 3 numbers separated with a space, three consecutive nextInt() would work, but such is not the case for BufferedReader, it accepts the space as a string and while parsing the string into integer throws NumberFormatException exception.
input e.g. "8347 394730 3487", all three numbers must be stored separately.
code e.g
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String b=br.readLine();
int x=Integer.parseInt(b);
b=br.readLine();
int x1=Integer.parseInt(b);
b=br.readLine();
int x2=Integer.parseInt(b);
System.out.println(x+x1+x2);
}
数字也可以大到 10^10。
所以我需要有关使用 BufferedReader 进行此类输入的帮助。此外,如果有任何其他替代但更快的读取整数的方法,那就足够了。
谢谢
最佳答案
获取字符串然后使用它:
String[] numberList = yourString.split("\\s+");
List<Integer> myList = new ArrayList<Integer>();
for(String num : numberList){
myList.add(Integer.parseInt(num));
}
更新*:请试试这个
public class Answer {
public static void main(String[] args) throws Exception {
List<String> eachLineList = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String b = br.readLine();
eachLineList.add(b.trim()); //Line 1 added to String list
b = br.readLine();
eachLineList.add(b.trim()); //Line 2 added to String list
b = br.readLine();
eachLineList.add(b.trim()); //List 3 added to String list
String[] numbers;
for (String line : eachLineList) {
numbers = line.split("\\s+");
if (numbers.length <= 1) {
//means if there was one or less integer each line don't do anything
break;
} else {
int intNum;
int temp = 0;
for (String num : numbers) {
intNum = Integer.parseInt(num);
temp += intNum;
}
System.out.println(temp);
}
}
}}
如果你在每一行输入类似这样的“8347 394730 3487”,总和将返回给你~
关于java - 在java中使用bufferedreader在java中读取多个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27457846/