Java Scanner() 从数组中读取

发布于 2024-09-26 12:02:14 字数 44 浏览 0 评论 0原文

我知道你可以用 Java 设置扫描仪的输入。 是否可以将阵列馈送到扫描仪?

I know you can set the input for a scanner in Java.
Is it possible to feed an array to the scanner?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

冧九 2024-10-03 12:02:14

对数组使用 Arrays.toString() 方法。
例如:

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

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

将打印出:

[1,
2,
3]

Use the Arrays.toString() method on the array.
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]
丿*梦醉红颜 2024-10-03 12:02:14

没有内置任何内容,但您当然可以 加入数组中的所有元素并将结果字符串传递到 扫描仪构造函数

性能更好但时间投入更多的解决方案是实施 通过包装数组并跟踪数组中的当前元素以及该元素的字符串表示形式中的当前位置,可以读取。然后,您可以使用来自支持数组的数据填充缓冲区作为扫描器 从您的 Readable 对象读取。这种方法允许您将数据从阵列延迟地流式传输到扫描仪中,但代价是需要您编写一些代码。

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.

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. You can then fill the buffer with data from the backing array as the Scanner reads from your Readable object. This approach lets you lazily stream data from your array into the Scanner, but at the cost of requiring you to write some code.

单挑你×的.吻 2024-10-03 12:02:14
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;
}
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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文