java - 在java中使用bufferedreader在java中读取多个整数

标签 java

我正在编写一个程序,我必须读取大约 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/

相关文章:

java - 使用 mongoDB 和 Morphia 进行映射缩减

java - 使用 JavaMail 访问 Mailinator POP3

java - SonarLint 抛出 IllegalStateException -> 无法读取本地问题存储索引

java.rmi.NoSuchObjectException 但添加了静态引用

java - 带有 java.lang.outofmemoryerror 的 React-native run-android 命令错误

java - 使用 JTDS 在 Spring Boot 中配置 HikariCP

java - Ruby 和 Scala(或 Java)中的 AES 解密

java - 使用非循环递归从 ArrayList<Number> 获取总和

java - CXF服务协助

java scala交叉编译相同模块错误java : cannot find symbol