1a) Create file, file1 , with the following values: 7 35 20 -43 -10 6 7 13 12.0
ID: 3792647 • Letter: 1
Question
1a) Create file, file1, with the following values: 7
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
1b) 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 sumf as float and set it to 0.0f.
-Use a for loop to go through each element of the Boolean array, and if an element is “true” then add thecorresponding element in the integer array to sum, and also add the corresponding element in the floating-point array to sumf.
-Print all three arrays, sum, and sumf.
Explanation / Answer
FileNumbersSum.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class FileNumbersSum {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("D:\file1.txt");
if(file.exists()){
Scanner scan = new Scanner(file);
int n = scan.nextInt();
int intArr[] = new int[n];
float floatArr[] = new float[n];
boolean booleanArr[] = new boolean[n];
for(int i=0; i<n ;i++){
intArr[i] = scan.nextInt();
}
for(int i=0; i<n ;i++){
floatArr[i] = scan.nextFloat();
}
for(int i=0; i<n ;i++){
booleanArr[i] = scan.nextBoolean();
}
int sum = 0;
float sumf = 0.0f;
for(int i=0; i<booleanArr.length; i++){
if(booleanArr[i]){
sum = sum + intArr[i];
sumf = sumf + floatArr[i];
}
}
System.out.println("Integer array: "+Arrays.toString(intArr));
System.out.println("Float array: "+Arrays.toString(floatArr));
System.out.println("Boolean array: "+Arrays.toString(booleanArr));
System.out.println("Integer sum: "+sum);
System.out.println("Float sum: "+sumf);
}
else{
System.out.println("File does not exist");
}
}
}
Output:
Integer array: [35, 20, -43, -10, 6, 7, 13]
Float array: [12.0, 1.5, -3.5, -2.54, 3.4, 45.34, 22.13]
Boolean array: [true, false, false, true, false, true, false]
Integer sum: 32
Float sum: 54.8
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.