/* Write a program that reads all the numbers from the file \"mynumbers.txt\" *
ID: 3577017 • Letter: #
Question
/* Write a program that reads all the numbers from the file "mynumbers.txt"
* and prints out the sum of the positive values from the file.
* You must print an error if the file can't be opened or contains any non-numeric values.
* You must write the complete program and output the same result as the one of sample run.
*/
/* sample sun
The sum of the positive values is 165.29.
*/
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
Explanation / Answer
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
public class FindSum {
public static void main(String[] args) {
double num;
double sum=0;
try(Scanner textfile = new Scanner(new File("mynumbers.txt"))){
//complete the rest of the code.
while(textfile.hasNextDouble()){
num = textfile.nextDouble();
System.out.println(num);
if(num>0){
sum+=num;
}
}
} catch(FileNotFoundException ex){
} catch(InputMismatchException ex){
}
System.out.println(sum);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.