Question: Using the method public static double sumNumbers(Scanner input): how to write the public static double sumNumbers(String parseString) method. Rather than take an already opened Scanner
Using the method public static double sumNumbers(Scanner input):
how to write the public static double sumNumbers(String parseString) method.
Rather than take an already opened Scanner this method takes a String to parse. Other than that, it performs the same computation as sumNumbers(Scanner).
Note that this illustrates that Java methods may have the same name so long as they have different argument types or different numbers of arguments.
Hint: It is tempting to copy and paste code for similar methods but clever programmers figure out how to use an already written function to solve a new problem by passing the old function appropriately constructed arguments. The best solutions to this problem are 1-2 lines long.
Also how to write this method: public static double sumNumbersInFile(String filename) throws Exception
This method performs the same computation as sumNumbers(Scanner) except it reads from the file named by the parameter filename. The actual file with the text should already be stored on disk. The method opens a pre-existing file on disk, reads it word by word and sums any valid real numbers that appear in it. Some example files are present with the code distribution called numbers1.txt and numbers2.txt.
numbers1.txt is:
3.953 2.915 6.4681
numbers2.txt is:
these are numbers 8.9 and 9.8
3.2 and 2.3 are numbers as well
Negative numbers like -32.3 are less than 0.0
Notice: This method may raise an exception if the named file does not exist and Java requires that the method "admits" this fact by declaring it in the signature. Do not remove the throws Exception otherwise the code won't work. More on that when we cover exceptions.
Hint: It is tempting to copy and paste code but you should reuse another function you wrote.
public static double sumNumbers(Scanner input) {
double total = 0.0;
//while loop till the token exist while (input.hasNext()) {
total += input.nextDouble(); } return total; }
//add numbers in the string and return total public static double sumNumbers(String parseString) {
}
public static double sumNumbersInFile(String filename) throws Exception{
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
