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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27457846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:50:13  来源:igfitidea点击:

Multiple integer read in java with bufferedreader in java

java

提问by Piyush Vishwakarma

I working on a program where I have to read about 10^6 integers. I tried working with the scanner class however when i tried for 800000*3 inputs, it took around 12.38 seconds. I also tried tried to work with the BufferedReader which actually worked faster but then it does not take the input i give as desired.

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

例如,如果我想读取用空格分隔的 3 个数字,三个连续的 nextInt() 可以工作,但 BufferedReader 的情况并非如此,它接受空格作为字符串,而将字符串解析为整数时会引发 NumberFormatException 异常。

输入例如“8347 394730 3487”,所有三个数字必须分开存储。

代码例如

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);
}

Also the numbers can be as large as 10^10.

此外,数字可以大到 10^10。

So I need help in using BufferedReader for such input. Also if at all there is any other alternate but faster method for reading integers, will be good enough.

所以我需要帮助来使用 BufferedReader 进行此类输入。此外,如果有任何其他替代但更快的读取整数的方法,那就足够了。

Thank you

谢谢

回答by Mehdi

get the String and then use this :

获取字符串,然后使用这个:

String[] numberList = yourString.split("\s+");
List<Integer> myList = new ArrayList<Integer>();
for(String num : numberList){
     myList.add(Integer.parseInt(num));
}

update* : please try this one

更新*:请试试这个

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);
        }
    }
}}

if you enter something like this "8347 394730 3487" in each line the sum will be return back to you ~

如果你在每一行输入这样的“8347 394730 3487”,总和将退还给你~

回答by user3437460

You may want to try receiving it as a String.

您可能想尝试将其作为字符串接收。

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String b=br.readLine();                      
String[] token = b.split(" ");      //Split into String array by space
int[] num = new int[token.length];  //Create int array

for(int x=0; x<token.length; x++)
    num[x] = Integer.parseInt(token[x]);  //Store all string array into int array

for(int x=0; x<num.length; x++)           //Printing
    System.out.print(num[x] + " ");

Given your input in one line with spaces, the output is as follows:

在一行中输入带有空格的输入,输出如下:

Output:8347 394730 3487

输出:8347 394730 3487

回答by Piyush Vishwakarma

I managed to get the answer somehow, with a little help from stackoverflow ofcourse

在stackoverflow的帮助下,我设法以某种方式得到了答案

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    String b=br.readLine();     
    String[] numbers=b.split(" ");
    long[] x=new long[numbers.length];
    for(int i=0;i<numbers.length;i++)
    {
        x[i]=Long.parseLong(numbers[i]);
        System.out.println(x[i]);
    }

回答by Stephen C

The String.split(separator)method can be used to split a string into an array of strings, with the separatorregex providing the separator. Refer to the Stringand Patternjavadoc for the complete description.

String.split(separator)方法可用于将字符串拆分为字符串数组,separator正则表达式提供分隔符。有关完整说明,请参阅StringPatternjavadoc。



However, if you are really concerned about performance, you could potentially reduce the time even further by using String.indexOfand String.substringto extract the numbers for parsing. Or potentially parse them yourself to avoid the overhead of creating strings.

但是,如果您真的很关心性能,则可以通过使用String.indexOfString.substring提取数字进行解析来进一步减少时间。或者可能自己解析它们以避免创建字符串的开销。

回答by Prashant

YOu can check below code once.

您可以检查以下代码一次。

public static void main(String[] args) throws IOException
{

    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    String []b=br.readLine().split(" ");
    for(int i=0;i<b.length;i++)
    {
        System.out.print(Integer.parseInt(b[i]));
    }
}