Read the Detailed Example in the text beginning on page 245: Spacely Sprockets.
ID: 666584 • Letter: R
Question
Read the Detailed Example in the text beginning on page 245: Spacely Sprockets. Using the input file that you downloaded from the class home page (sprocketorders.txt), write a Java program to summarize the data from the input file and output a report that should resemble Figure 13-16 on page 246 in the text. The report should appear in the NetBeans Output Window when the program runs. As described in the text, you can use a sequence of if-then statements to solve this problem; however, for full credit on this assignment, you must use the switch structure. If you have problems or questions understanding this new structure, discuss it with your peers or ask me. Submit your zipped NetBeans project folder by the due date.
(sprocketorders.txt below)
Explanation / Answer
Code:
import java.io.*;
public class Output
{
public static void main(String[] args)
{
BufferedReader buffread = null;
BufferedWriter buffwrite = null;
try
{
buffread = new BufferedReader(new FileReader("C:/Users/Ekta/Docs/sprocketorders.txt"));
String input_line;
String element[] = new String[2];
int sum[] = new int[5];
File file = new File ("C:/Users/Ekta/Docs/output.txt");
while ((input_line = buffread.readLine()) != null)
{
input_line = input_line.trim().replaceAll("\s+", " ");
element = input_line.split(" ");
switch(Integer.parseInt(element[0]))
{
case 1:
sum[0] = sum[0] + Integer.parseInt(element[1]);
break;
case 2:
sum[1] = sum[1] + Integer.parseInt(element[1]);
break;
case 3:
sum[2] = sum[2] + Integer.parseInt(element[1]);
break;
case 4:
sum[3] = sum[3] + Integer.parseInt(element[1]);
break;
case 5:
sum[4] = sum[4] + Integer.parseInt(element[1]);
break;
}
}
if (!file.exists())
{
file.createNewFile();
}
//FileWriter fw = new FileWriter(file.getAbsoluteFile());
buffwrite = new BufferedWriter(new OutputStreamWriter(System.out));
buffwrite.write("Spacely Sprockets Taking Sprockets into the Future Sales Summary Report SprocketNumber Total Quantity Sold ");
for(int i = 0; i < sum.length; i++)
buffwrite.write((i + 1) + " " + sum[i] + " ");
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (buffread != null)
buffread.close();
if (buffwrite != null)
buffwrite.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.