0

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

2
  • What kind of array? Array of strings? Array of chars representing a string? Commented Oct 10, 2010 at 9:51
  • It's solved. My main problem was that I didn't understand that scanners just accept Strings, I thought I had to create a new object of some kind. Commented Oct 10, 2010 at 10:13

3 Answers 3

1

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

The array is totally predefined before I start reading anything, so I'm going to go with the join. Should I just separate the elements with a \n ?
0
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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.