I'm working on an assignment where I have to use methods to get a list of numbers as a string type and then another method to calculate the average of those numbers provided. I have been able to write the method that asks for the numbers but I'm stuck as for how to get the average of those numbers. I know average would be sum / by the number of numbers provided.
hers is the code I have so far. Can anyone provide some feedback or how I should go about this? I'm new to Java but it is tough at times but don't want to give up.
Please explain what you mean about adding numbers? Do you mean you want to add multiple numbers, or do you want to calculate the trasverse sum of a single number's digits?
Don't use nextLine(); use this method instead, in which case your method will retun an int.
Please look here to see how the code button is supposed to work; I have corrected the code tags for you because you are new, and doesn't it look better now Don't use so many empty lines in your code.
posted 2 weeks ago
This is what your code would look like with what I think is the right number of empty lines:-Don't mix indentation conventions: looks at lines 4 and 9.
posted 2 weeks ago
Campbell Ritchie wrote:Don't use nextLine(); use this method instead, in which case your method will retun an int.
Depends how you interpret this from the OP:
" I have to use methods to get a list of numbers as a string type"
To me (along with the code as written) the numbers come in as a single String, hence my question about the format of the input.
If I understood right, you want to get some numbers from the user as a string and then to find their average.
To do it you can create a String array or list ( ArrayList<String> ) to collect numbers which are the user entered. And then write another method which takes this array or list as a parameter and returns double.Then iterate this array/list and take each element as Double.parseDouble(yourStringElement), add them to some variable( for example sum) and finally devide this sum to the length of array/list. Then return what you get.
Seems like the requirements are open to interpretation. All keyboard input comes in as characters.
You could get them as a list of numbers entered on a single line using Scanner#nextLine(), but then you'd have to separate then numbers and take each number (String) and parse it into an int (using Integer#parseInt()) for processing.
You could use Scanner#next() to split the numbers into individual Strings but then you'd still have to parse them into ints.
You could use Scanner#nextInt() which both splits the numbers and parses them into ints.
The last approach would be my preference but it depends on how you interpret the specs. With the last approach you end up with a list of ints that you can sum and count for your average but you'd have to print them to the display, which is trivial.