In: Computer Science
In Java.
Create a class called FileSumWrapper with a method that has the signature
public static void handle(String filename, int lowerBound)
Make this method call FileSum.read and make your method catch all the errors.
FileSum.read is a method that takes a filename and a lower bound, then sums up all the numbers in that file that are equal to or above the given lower bound.
FileSum :
import java.io.File; import java.rmi.UnexpectedException; import java.util.Scanner; public class FileSum { public static int read(String filename, int lowerBound) throws Exception { Scanner inputFile = new Scanner(new File(filename)); int acc = 0; boolean atLeastOneFound = false; while (inputFile.hasNext()) { int data = inputFile.nextInt(); if (data >= lowerBound) { acc += data; atLeastOneFound = true; } } if (!atLeastOneFound) { throw new UnexpectedException(""); } return acc; } }
Question1:
import java.util.Scanner; public class Question1 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("Enter a filename"); String filename = keyboard.nextLine(); System.out.println("Enter a lower bound"); int lowerBound = keyboard.nextInt(); FileSumWrapper.handle(filename, lowerBound); } }
err.txt :
50 40 30 90 85 23 06 30x 54 675 875 34 2323 423 423 5 5 79 97 90y 7986 5 46 64656 66 6 333 93 9 300 20 2 9 209 290 39 48 85 7847 578048
t1.txt:
50 40 30 90 85 23 06 30x 54 675 875 34 2323 423 423 5 5 79 97 90y 7986 5 46 64656 66 6 333 93 9 300 20 2 9 209 290 39 48 85 7847 578048
Here is the input :
t1.txt 50 |
output:
Enter a filename\n Enter a lower bound\n Sum of all numbers in t1.txt is 665177\n
import java.io.File;
import java.rmi.UnexpectedException;
import java.util.Scanner;
class FileSum {
public static int read(String filename, int lowerBound) throws
Exception {
Scanner inputFile = new Scanner(new File(filename));
int acc = 0;
boolean atLeastOneFound = false;
while (inputFile.hasNext()) {
int data = inputFile.nextInt();
if (data >= lowerBound) {
acc += data;
atLeastOneFound = true;
}
}
if (!atLeastOneFound) {
throw new UnexpectedException("");
}
return acc;
}
}
//created wrapper class
class FileSumWrapper {
//create a hanlde method
// which calles read method in FileSum class
public static void handle(String filename, int
lowerBound){
try {
int sum=FileSum.read(filename,
lowerBound);
System.out.println("Sum of all numbers in
"+filename+" is "+sum);
} catch
(Exception e) {
e.printStackTrace();
}
}
}
public class Question1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a filename");
String filename = keyboard.nextLine();
System.out.println("Enter a lower bound");
int lowerBound = keyboard.nextInt();
FileSumWrapper.handle(filename, lowerBound);
}
}
Note : If you like my answer please rate and help me it is very Imp for me