Q1 SOlution. import java.util.Scanner; public class Tester{ public static void m
ID: 3751999 • Letter: Q
Question
Q1 SOlution.
import java.util.Scanner;
public class Tester{
public static void main(String[] args) throws IllegalArgumentException{
Scanner scan = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
int[] array = new int[10];
//Getting the number from user and store in Array
for(int i=0; i<10; i++){
array[i]= scan.nextInt();
}
int max = array[0];
int min = array[0];
int sum = 0;
//Finding the min, max and average of the array
for(int i=0; i<array.length; i++){
sum = sum+array[i];
if(max<array[i])
max = array[i];
if(array[i]<min)
min = array[i];
}
System.out.println("Largest: "+max+" Smallest: "+min+" Average: "+sum/array.length);
scan.close();
}
}
Create a copy of your solution to question 1. Edit the copy of the program so that the input numbers are obtained from a text file named numbers.txt instead of from the keyboard. • Use a text editor to create the numbers.txt file yourself. • Place in the file any number of numbers and test your program. • Test the program with different sized files with different sets of numbers. • Make sure your code works correctly if 1 (a) the file isn’t found, (b) if it exists but doesn’t have any data in it, or (c) if the file has too many values to fit into the array
Explanation / Answer
import java.utils.*;
public class Tester{
public static void main(String[] args) throws java.lang.Exception {
StringBuilder sb = new StringBuilder();
String strLine = "";
List < Integer > list = new ArrayList < > ();
try {
BufferedReader br = new BufferedReader(new FileReader("numbers.txt"));
while (strLine != null) {
strLine = br.readLine();
sb.append(strLine);
sb.append(System.lineSeparator());
strLine = br.readLine();
if (strLine == null)
break;
list.add(Integer.valueOf(strLine));
}
//Getting the number from user and store in Array
Integer[] array = new Integer[list.size()];
array = list.toArray(array);
for (int i = 0; i < 10; i++) {
array[i] = scan.nextInt();
}
int max = array[0];
int min = array[0];
int sum = 0;
//Finding the min, max and average of the array
for (int i = 0; i < array.length; i++) {
sum = sum + array[i];
if (max < array[i])
max = array[i];
if (array[i] < min)
min = array[i];
}
System.out.println("Largest: " + max + " Smallest: " + min + " Average: " + sum / array.length);
br.close();
} catch (FileNotFoundException e) {
System.err.println("File not found");
} catch (IOException e) {
System.err.println("Unable to read the file.");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.