简体   繁体   English

Java Scanner()从数组读取

[英]Java Scanner() to read from Array

I know you can set the input for a scanner in Java. 我知道您可以使用Java设置扫描仪的输入。 Is it possible to feed an array to the scanner? 是否可以将阵列送入扫描仪?

There is nothing built in, but you could certainly join all of the elements in your array and pass the resulting string into the Scanner constructor . 没有内置任何内容,但是您当然可以加入数组中的所有元素,并将结果字符串传递给Scanner构造函数

A solution with better performance but a greater time investment is to implement Readable by wrapping your array, and keeping track of the current element in the array and the current position in that element's string representation. 一种性能更好但花费更多时间的解决方案是通过包装数组并跟踪数组中的当前元素以及该元素的字符串表示形式中的当前位置来实现Readable You can then fill the buffer with data from the backing array as the Scanner reads from your Readable object. 然后,当扫描程序从您的Readable对象读取数据时,您可以使用后备阵列中的数据填充缓冲区。 This approach lets you lazily stream data from your array into the Scanner, but at the cost of requiring you to write some code. 通过这种方法,您可以将数据从阵列延迟地流到扫描仪中,但是需要您编写一些代码。

Use the Arrays.toString() method on the array. 在数组上使用Arrays.toString()方法。 For example: 例如:

int[] arrayOfInts = {1, 2, 3};
Scanner s = new Scanner(Arrays.toString(arrayOfInts));

while (s.hasNext()) {
    System.out.println(s.next());
}

Will print out: 将打印出来:

[1,
2,
3]
public class Totalsum {

  public static void main(String[] args){

  int[] y={6,1,5,9,5};
  int[] z={2,13,6,15,2};

  int Total= sumLargeNumber(y,z,5);

  System.out.println("The Total sum is "+Total); //call method
}

public static int sumLargeNumber(int a[], int b[], int size) {
  int total=0;

  for(int i=0; i< size; i++) {
    if(a[i] > b[i]){
      total=total+a[i];
    }

    else {
      total=total+b[i];
    }
  }
  return total;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM