Java 将用空格分隔的整数读入int[]数组

Java 将用空格分隔的整数读入int[]数组,java,arrays,int,inputstream,Java,Arrays,Int,Inputstream,我读了一行 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); reader.readLine(); 示例输入是 1 4 6 32 5 读取输入并将其放入整数数组int[]的最快方法是什么 如果可能的话,我也在寻找一些单线解决方案。试试看 line = reader.readLine(); String[] s = line.split(" "); ... 您也可以使用String

我读了一行

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
reader.readLine();
示例输入是

1 4 6 32 5
读取输入并将其放入整数数组
int[]
的最快方法是什么

如果可能的话,我也在寻找一些单线解决方案。

试试看

 line = reader.readLine();
 String[] s = line.split(" ");
 ...

您也可以使用StringTokenizer,但最快的方法之一是读取字节并迭代它们,然后自己转换ascii(utf8?)编码的数字;)

您可以使用
扫描仪

Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();
while (scanner.hasNextInt())
  list.add(scanner.nextInt());
int[] arr = list.toArray(new int[0]);
Scanner Scanner=新的扫描仪(System.in);
列表=新的ArrayList();
while(scanner.hasNextInt())
添加(scanner.nextInt());
int[]arr=list.toArray(新的int[0]);
在java中有闭包之前,这可能是您能得到的最短闭包

int[]arr=list.toArray(新的int[0])不起作用,因为没有从整数到int的转换。不能将int用作泛型的类型参数

但是,如果您使用的是Java8,那么您可以使用下面的代码片段(更好的方法)为其使用流API


int[]array=list.stream().mapToInt(i->i.toArray()

您还可以预编译regex
模式
来拆分字符串

    Pattern pattern = Pattern.compile("(\\d+)\\s+"); //$NON-NLS-1$
    Matcher matcher = pattern.matcher(line);
    List<Integer> numbers = new LinkedList<Integer>();

    while (matcher.find()) {
        numbers.add(Integer.valueOf(matcher.group(1)));
    }
    Integer[] output = numbers.toArray(new Integer[numbers.size()]);
Pattern=Pattern.compile(“(\\d+)\\s+”)//$非NLS-1$
匹配器匹配器=模式匹配器(线);
列表编号=新建LinkedList();
while(matcher.find()){
add(Integer.valueOf(matcher.group(1));
}
整数[]输出=numbers.toArray(新整数[numbers.size()]);
也可以直接使用pattern.split

    Pattern pattern = Pattern.compile("(\\d+)"); //$NON-NLS-1$
    String[] numberAsString = pattern.split(line);
    int[] numbers = new int[numberAsString.length];
    for (int i = 0; i < numberAsString.length; i++) {
        numbers[i] = Integer.valueOf(numberAsString[i]).intValue();
    }
Pattern=Pattern.compile(“\\d+”)//$非NLS-1$
字符串[]numbersString=pattern.split(行);
int[]numbers=新的int[numbersString.length];
for(int i=0;i

必须喜欢正则表达式:D

因为您不知道输入的大小,所以可以将输入读取为字符串,然后将字符串数组解析为整数数组

String[] arr=reader.readLine().split(" ");
int[] intarr=new int[arr.length];

for(int i=0;i<arr.length;i++)
 intarr[i]=Integer.parseInt(arr[i]);
String[]arr=reader.readLine().split(“”);
int[]intarr=新int[arr.length];
对于(inti=0;i
BufferedReader=newbufferedreader(newinputstreamreader(System.in));
字符串[]s=reader.readLine().split(“”);
int[]i=新的int[s.length];
对于(int k=0;k简短回答

BufferedReader比Scanner更快

使用
BufferedReader
然后拆分和解析每个整数值要比使用
Scanner
nextInt()
方法快得多


解释

  • 使用
    BufferedReader
    readLine()
    方法扫描整个字符串
  • 将此字符串拆分为
    str.Split(\\s”)
  • 迭代上述数组,并使用
    integer.parseInt()
  • 对上述方法进行了测试,分析了1000个不同的整数,结果表明,该方法比使用
    Scanner
    类的
    nextInt()
    方法快一倍

    测试BufferedReader类的代码

    以下是针对1000个不同输入测试这两个代码的结果

                        Scanner         BufferedReader  
                        (time ns)       (time ns)
    
    Test Case 01        33855662        14202880    
    Test Case 02        32779163        17772490    
    Test Case 03        33421010        16625859    
    Test Case 04        31901801        14552859    
    Test Case 05        34890568        13943169    
    Test Case 06        32913570        15342349    
    Test Case 07        31733063        14153896    
    Test Case 08        32063369        14368770    
    Test Case 09        34354742        19922145    
    Test Case 10        31760603        14441492    
    
    Average             32967355.1      15532590.9  
    

    对于Java 8流,这实际上可以在一行中完成:

    int[] array = Arrays.stream(reader.readLine().split("\\s")).mapToInt(Integer::parseInt).toArray();
    
    其中,
    reader
    是您的
    BufferedReader
    对象

    说明

    • reader.readLine()
      将输入读取为
      String
    • reader.readLine().split(\\s”)
      在返回
      String[]的空白处拆分
      String
    • Arrays.stream(reader.readLine().split(\\s”)
      从该
      字符串[]创建
    • Arrays.stream(reader.readLine().split(\\s”).mapToInt(Integer::parseInt)
      Integer::parseInt
      应用于该
      流的每个元素,并返回由应用函数的结果组成的
      IntStream
    • Arrays.stream(reader.readLine().split(\\s”).mapToInt(Integer::parseInt).toArray()返回包含该
      IntStream的元素的
      int[]

    只需实现名为FastReader的类,如下所示:

    static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;
    
        public FastReader()
        {
            br = new BufferedReader(new InputStreamReader(System.in));
        }
    
        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
    
        int nextInt()
        {
            return Integer.parseInt(next());
        }
    
        long nextLong()
        {
            return Long.parseLong(next());
        }
    
        double nextDouble()
        {
            return Double.parseDouble(next());
        }
    
        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
    
    现在,将用空格分隔的整数读入int[]数组,就像您通常所做的那样:

    FastReader fr = new FastReader();
    int size = fr.nextInt();
    int arr[] = new int[size];
    for(int i=0; i<size; i++)
        arr[i] = fr.nextInt();
    
    FastReader fr=new FastReader();
    int size=fr.nextInt();
    int arr[]=新的int[size];
    对于(int i=0;i
    

    上面的代码是如何使用java编程获取空间分隔的整数输入,并执行您选择的任何任务。在我的例子中,我添加了数字。

    简单的答案是使用scanner类的
    nextInt()
    方法读取
    for
    循环中的整数

    以下是实施方案:

    import java.util.Scanner;
    
    public class DriverMain {
        public static void main(String args[]){
            Scanner scanner = new Scanner(System.in);
            
            System.out.println("Enter the size of an array: ");
            int size = scanner.nextInt();
    
            System.out.println("Enter array elements separated by single space.");
            int[] numbers = new int[size];
            for(int i=0;i<size;i++){
                numbers[i] =  scanner.nextInt();
            }
    
            for(int i=0;i<size;i++){
                System.out.println(numbers[i]);
            }
    
        }
    }
    
    import java.util.Scanner;
    公共类驱动程序{
    公共静态void main(字符串参数[]){
    扫描仪=新的扫描仪(System.in);
    System.out.println(“输入数组的大小:”);
    int size=scanner.nextInt();
    System.out.println(“输入由单个空格分隔的数组元素”);
    int[]数字=新的int[大小];
    
    对于(int i=0;我查找
    String.split
    Integer.parseInt
    。我已经这样做了,但我正在寻找一些更短的方法。更短(“更快”)意味着更少的代码行?我正在寻找最快的方法,也在寻找最短的方法。最快的方式?最快的编写?最快的运行?我认为需要
    int[]
    int[] array = Arrays.stream(reader.readLine().split("\\s")).mapToInt(Integer::parseInt).toArray();
    
    static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;
    
        public FastReader()
        {
            br = new BufferedReader(new InputStreamReader(System.in));
        }
    
        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
    
        int nextInt()
        {
            return Integer.parseInt(next());
        }
    
        long nextLong()
        {
            return Long.parseLong(next());
        }
    
        double nextDouble()
        {
            return Double.parseDouble(next());
        }
    
        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
    
    FastReader fr = new FastReader();
    int size = fr.nextInt();
    int arr[] = new int[size];
    for(int i=0; i<size; i++)
        arr[i] = fr.nextInt();
    
     Scanner sc = new Scanner(System.in);
        String n=sc.nextLine();
        String[] no=n.split(" ");
        int sum=0;
        for(String i:no){
            sum+=Integer.parseInt(i);}
        System.out.println(sum);
    
    import java.util.Scanner;
    
    public class DriverMain {
        public static void main(String args[]){
            Scanner scanner = new Scanner(System.in);
            
            System.out.println("Enter the size of an array: ");
            int size = scanner.nextInt();
    
            System.out.println("Enter array elements separated by single space.");
            int[] numbers = new int[size];
            for(int i=0;i<size;i++){
                numbers[i] =  scanner.nextInt();
            }
    
            for(int i=0;i<size;i++){
                System.out.println(numbers[i]);
            }
    
        }
    }