Reputation: 37
Maybe my google-fu is just terrible, but I'm having a very hard time figuring out how to do this. I'm trying to get a scanner to read a string, add the inputs, and return a value. I feel like I am just missing something... for example, I'm not sure how to get a variable set to the first double in the scanner.
import java.util.Scanner;
public class adding {
public static double sum(Scanner input){
Scanner s=new Scanner (System.in);
double i = (s.nextDouble());
double sumAnswer = 0;
while (s.hasNext()){
sumAnswer = sumAnswer + i;
i = s.nextDouble();
}
return sumAnswer;
}
public static void main(String[] args){
System.out.println(sum(new Scanner("1.2 2.8 3.9")));
}
}
Upvotes: 0
Views: 1805
Reputation: 55609
You don't really need an i
variable.
And, as already mentioned, don't have 2 Scanner
's.
public static double sum(Scanner input){
double sumAnswer = 0;
while (input.hasNext()){
sumAnswer += input.nextDouble();
}
return sumAnswer;
}
Upvotes: 3
Reputation: 398
You shouldn't be resetting the scanner after passing the input.
public class adding {
public static double sum(Scanner input){
double i = (input.nextDouble());
double sumAnswer = 0;
while (input.hasNext()){
sumAnswer = sumAnswer + i;
i = input.nextDouble();
}
return sumAnswer;
}
That ought to work better for you, maybe. I could also be mixing something up there...
Upvotes: 0