Can somone help me take this code: Extend the program by adding and displaying t
ID: 3688747 • Letter: C
Question
Can somone help me take this code:
Extend the program by adding and displaying the grand total after all the row totals have been displayed.
Further extend the program by calculating and displaying the mean, to two decimal places. Be careful of the integer division trap.
Your output should look like this, but verify that the mean is calculated correctly:
Row 1 sum: 30
Row 2 sum: 48
Row 3 sum: 55
Count: 12
Grand total: 325
Mean: 27.08
import java.util.*;
import java.io.*;
public class Lab9_Problem1
{
public static void main(String [] args)
{
int iVal;
int iRow;
int iRowSum;
int iToken;
iRowSum = 0;
iRow = 1;
try
{
Scanner ifsInput = new Scanner(new File("c:homestudentlastname/9_1_Input.txt"));
while(ifsInput.hasNextLine())
{
while(ifsInput.hasNextInt())
{
for(iToken = 0; iToken <= 3; iToken++)
{
iVal = ifsInput.nextInt();
iRowSum = iRowSum + iVal;
}
System.out.println("Row " + iRow + " sum: " + iRowSum);
iRowSum = 0;
iRow++;
}
}
}
catch (FileNotFoundException sMsg)
{
System.out.println("The file cannot be found or opened.");
}
}
}
Explanation / Answer
Hi I have added required functionality.
import java.util.*;
import java.io.*;
public class Lab9_Problem1 {
public static void main(String [] args)
{
int iVal;
int iRow;
int iRowSum;
int iToken;
int totalSum = 0;
int totalEle = 0;
iRowSum = 0;
iRow = 1;
try
{
Scanner ifsInput = new Scanner(new File("c:homestudentlastname/9_1_Input.txt"));
while(ifsInput.hasNextLine())
{
while(ifsInput.hasNextInt())
{
for(iToken = 0; iToken <= 3; iToken++)
{
iVal = ifsInput.nextInt();
iRowSum = iRowSum + iVal;
// increasing count of total element
totalEle++;
}
// adding into totalSum
totalSum = totalSum + iRowSum;
System.out.println("Row " + iRow + " sum: " + iRowSum);
iRowSum = 0;
iRow++;
}
}
// added new code to print grand total and mean value
System.out.println("Count: "+totalEle);
System.out.println("Grand total: "+totalSum);
System.out.println("Mean: "+String.format(".2f", (double)/totalSum/totalEle);
}
catch (FileNotFoundException sMsg)
{
System.out.println("The file cannot be found or opened.");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.