Create file, file1, with the following values: 35 20 -43 -10 6 7 13 12.0 1.5 -3.
ID: 3791927 • Letter: C
Question
Create file, file1, with the following values: 35 20 -43 -10 6 7 13 12.0 1.5 -3.5 -2.54 3.4 45.34 22.13 true false true false true false Write a program in Java to do the following: -Open "file1" and read the first value, n, which is supposed to be an integer describing the size of the upcoming arrays of integer, float, and Boolean values. -Create one-dimensional arrays of n integer, floating point, and Boolean values. -Populate the three created arrays by reading their values from file1. -Declare sum as integer and set it to 0. -Declare sum f as float and set it to O. Of. -Use a for loop to go through each element of the Boolean array, and if an element is "true" then add the corresponding element in the integer array to sum, and also add the corresponding element in the floating-point array to sum f. -Print all three arrays, sum, and sum f.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 FileReadOperation {
public static void main(String[] args) throws FileNotFoundException {
// opening file
Scanner sc = new Scanner(new File("file1"));
String line;
int n = sc.nextInt(); // reading n value
// creating three array
int[] intArr = new int[n];
float[] doubleArr = new float[n];
boolean[] boolArr = new boolean[n];
// reading all three lines and putting content in respective array
int i=0;
// reading first n integers
while(i < 7){
intArr[i++] = sc.nextInt();
}
i = 0;
// reading next n double values
while(i<7)
doubleArr[i++] = sc.nextFloat();
i = 0;
// reading next n boolean values
while(i<7)
boolArr[i++] = sc.nextBoolean();
int sum = 0;
float sumf = 0;
for(i=0; i<n; i++){
if(boolArr[i]){
sum = sum + intArr[i];
sumf = sumf + doubleArr[i];
}
}
// printing all array
for(i=0; i<7; i++)
System.out.print(intArr[i]+" ");
System.out.println();
for(i=0; i<7; i++)
System.out.print(doubleArr[i]+" ");
System.out.println();
for(i=0; i<7; i++)
System.out.print(boolArr[i]+" ");
System.out.println();
System.out.println("Sum: "+sum);
System.out.println("Sumf: "+sumf);
}
}
/*
Sample run:
35 20 -43 -10 6 7 13
12.0 1.5 -3.5 -2.54 3.4 45.34 22.13
true false false true false true false
Sum: 32
Sumf: 54.8
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.