For this problem you will read a file of numbers adding them ad you go, but skip
ID: 3676210 • Letter: F
Question
For this problem you will read a file of numbers adding them ad you go, but skipping some of the number as indicated by a code in the file. Create a package named prob? Create a text file named number in your prob Folder with the sample values shown below. Create a class named Numberadder that has a main that reads numbers.txt and adds all 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: Here is another test case which should produce the output:Explanation / Answer
1)//creating package prob2
//save as NumberAdding.java
Package prob2;
public class NumberAdding{
public static void main(String args[]){
System.out.println("Number adding for a given file");
}
}
compile the program as
javac -d . NumberAdding.java
run this program as
java prob2.NumberAdding
2)create a numbers.txt file and stores the files given in program and then store in to prob2 package folder.
numbers.txt
4
5
S2
99
2
17
1
8
S1
7
10
10
5
3)
//file save NumbersAdder.java
package prob2.*;//importing prob2 package
import java.util.*;
import java.io.File;
import java.io.IOException;
public class NumbersAdder
{
public static void main(String[] args)
throws IOException
{
//For adding numbers in the txt file we know that how many lines in numbers.txt file
// Getting Resource as file1 object
File file1 = new File(getClass().getResource("/prob2.numbers").getFile());//fill exact path of prob2 floder
//To store the contents read via File Reader
FileReader fr = new FileReader(file1);
//Read reader and store a line in 'data', print data
BufferedReader reader = new BufferedReader(fr);
int lines = 0;//number of lines
count=0;//initiate count value
int sum=0;
while (reader.readLine() != null) lines++;
reader.close();
//adding numbers in numbers.txt one by one, skipped number if s followed by the number
while(count<lines)
{
if(aScanner.hasNextInt())
{
sum += aScanner.nextInt();
count++
}
else
{
String t1 = input.nextLine();
int jumpcount= aScanner.nextInt();
count=count+jumpcount;
}
}//while
System.out.println("Sum =" + sum);
}//main
}//class
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.