'How can we write method to read integers from a Scanner stream?
My goal is to implement a method named add that receives a reference to a Scanner object associated with a stream of input consisting of integers only. The method reads all the integers remaining to be read from the stream and returns their sum.
So if the input were 3 51 204 17 1040, the returned value would be 1315. The method must not use a loop of any kind (for, while, do-while t accomplish its job).
My attempt is shown below:
public void add(Scanner scanner){
Scanner input = new Scanner(System.input);
String s = input.nextLine();
String[] numbers = str.split(" ")
int[] ints = new int[numbers.length];
}
The specific issue that I am running into is the conversion of the string array into an integer array.
Solution 1:[1]
Since you can't use a loop of any kind, I think you are supposed to use recursion. You need to actually return a value. Presumably an int. Something like check if there is an int. If so, read it and recursively add any other int(s); Otherwise, return 0. Like,
public int add(Scanner input){
if (input.hasNextInt()) {
return input.nextInt() + add(input);
}
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Elliott Frisch |
