Java Programming Problem 1 (name this Lab9_Problem1) Create a new Notepad text f
ID: 3761794 • Letter: J
Question
Java Programming
Problem 1 (name this Lab9_Problem1)
Create a new Notepad text file.
Populate it with these values, separated by a space, each line as shown:
10 5 4 11
15 33 2 -2
4 8 7 36
Save the file as 9_1_Input.txt in your c:homestudentlastname folder
Write a Java class with only a main() method.
Open the file for reading and traverses it through the end using a while loop based on the .hasNextInt() method. Hard-code the filename into your program.
Declare these variables. It will be up to you to manage them at the appropriate place in your program:
int iVal; // To capture each individual token as it's read from file
int iRow; // A total number of rows counter; initialize it to 0
int iRowSum; // A row sum accumulator variable
int iToken; // The counter variable for a for loop
Instantiate your file Scanner object as ifsInput.
Use a for loop structure to traverse each row and sum the values to a row total.
Display the row total as follows:
Row 1 sum: 30
Row 2 sum: 48
Row 3 sum: 55
Explanation / Answer
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class planeTicket {
private static Scanner ifsInput;
private static Scanner line;
public static void main(String[] args) throws FileNotFoundException {
line = new Scanner(new File("9_1_Input.txt"));
int iVal; // To capture each individual token as it's read from file
int iRow = 0; // A total number of rows counter; initialize it to 0
int iRowSum; // A row sum accumulator variable
int iToken; // The counter variable for a for loop
while (line.hasNext()) {
ifsInput = new Scanner(line.nextLine());
iRow++;
iRowSum=0;
while (ifsInput.hasNextInt()) {
iVal = ifsInput.nextInt();
iRowSum = iRowSum + iVal;
}
System.out.println("Row "+(iRow)+" sum: "+iRowSum);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.