Reputation: 1
I am a very new to Java, so my knowledge is very limited. I have been trying to find the problem in this block of code.
import java.util.Scanner;
public class avgFinder {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input numbers to average. Separate by a space.");
String nums = scan.next();
String[] parseNums = nums.split("[ ]");
double sum = 0;
int cnt = 0;
for (int a=0; a<=parseNums.length-1; a++) {
sum += Double.parseDouble(parseNums[a]);
cnt++;
}
double mean = sum/cnt;
System.out.println("Mean: " + mean);
}
}
But when I input a a set of numbers, only the first number gets printed instead of the actual mean. Example:
Input numbers to average. Separate by a space.
1 2 3
Mean: 1.0
Another thing is if I replace nums.split("[ ]")
with nums.split("[,]")
and put commas instead of spaces between the numbers in the output, it actually outputs the mean. I like spaces better though, it looks cleaner. Why is this happening?
Upvotes: 0
Views: 132
Reputation: 2396
Scanner.next() returns the next word. By default, words are separated by whitespace. So when you call Scanner.next(), your scanner reads the digits of the first number, hits a space, and says "ok, that's the end of the word. Time to return the result" and you end up with just the first number.
That's why it works when you replace the spaces with commas: Without any spaces, the scanner doesn't find whitespace until it reaches the line break, so it returns the whole line.
Scanner.nextLine() returns the entire line instead of just one word (it reads until it hits a line break), so I'd suggest using that instead.
Upvotes: 0
Reputation: 1482
Calling Scanner.next()
will return the next element in a line before a space, so you only getting the first number in your input. Use Scanner.nextLine()
which will return all the values on that line.
Upvotes: 1
Reputation: 1579
Try this
use nextLine()
instead of next()
nextLine returns complete line of text while next returns only one word
Also use nums.split(" ");
import java.util.Scanner;
public class avgFinder {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input numbers to average. Separate by a space.");
String nums = scan.nextLine();
String[] parseNums = nums.split(" ");
double sum = 0;
int cnt = 0;
for (int a=0; a<=parseNums.length-1; a++) {
sum += Double.parseDouble(parseNums[a]);
cnt++;
}
double mean = sum/cnt;
System.out.println("Mean: " + mean);
}
}
Upvotes: 3