For this problem you will read a file of numbers adding them as you go, but skip
ID: 3805168 • Letter: F
Question
For this problem you will read a file of numbers adding them as you go, but skipping some of the number as indicated by a code in the file 1. Create a package named prob1 2. Create a text file named numbers.txt in your prob1 folder with the sample values shown below. The third line is the letter "s" followed by the number "2". Similarly, the ninth line is the letter "s" followed by the number "1". This will be explained next. S2 99 17 S1 10 100 Note: You do not need to write a program to create this text file. You m create the file manual creatin ur local disk, and then co and paste all the values above into it it on 3. Create a class named NumberAdder that has a main that reads numbers.txt and adds a numbers except the ones skipped as indicated by a line in the file that starts with the letter "s" and is followed by the number of lines to skip. Finally, the sum should be printed to the console. For example, the input below:Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class NumberAdder {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("numbers.txt"));
int sum = 0;
int skip = 0;
// reading line by line
while(sc.hasNextLine()){
// reading current line
String line = sc.nextLine();
if(skip > 0){
skip--;
continue;
}
try{
// converting current line content in integer
int num = Integer.parseInt(line.trim());
sum = sum + num;
}catch(Exception e){
// current line content is not a number
//System.out.println("skipped "+line);
skip = line.charAt(1)-'0';
}
}
System.out.println("Sum = "+sum);
}
}
/*
Sample output:
Sum = 90
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.