Related questions
Concept explainers
JAVA PROGRAM
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;
public class FileTotalAndAverage {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String fileName;
do {
System.out.print("Please enter the file name: ");
fileName = scanner.nextLine();
try {
// Read numbers from the file
double[] numbers = readNumbersFromFile(fileName);
if (numbers != null) {
// Calculate total and average
double total = calculateTotal(numbers);
double average = calculateAverage(numbers);
// Set the locale to ensure proper formatting of numbers
Locale.setDefault(Locale.US);
// Display the results with three decimal digits
System.out.printf("Total: %.3f%n", total);
System.out.printf("Average: %.3f%n", average);
break; // Exit the loop if successful
}
} catch (IOException e) {
System.out.println("File '" + fileName + "' does not exist.");
} catch (InputMismatchException e) {
System.out.println("Invalid data in the file. Please make sure the file contains only numeric values.");
}
} while (true);
scanner.close();
}
private static double[] readNumbersFromFile(String fileName) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
double[] numbers = null;
try {
String[] tokens = reader.readLine().split("\\s+");
numbers = new double[tokens.length];
for (int i = 0; i < tokens.length; i++) {
numbers[i] = Double.parseDouble(tokens[i]);
}
} finally {
reader.close();
}
return numbers;
}
private static double calculateTotal(double[] numbers) {
double total = 0;
for (double num : numbers) {
total += num;
}
return total;
}
private static double calculateAverage(double[] numbers) {
double total = calculateTotal(numbers);
return total / numbers.length;
}
}
Test Case 1
double_input1.txtENTER
Total: -5,748.583\n
Average: -57.486\n
Test Case 2
double_input2.txtENTER
Total: 112,546.485\n
Average: 56.273\n
Test Case 3
double_input3.txtENTER
File 'double_input3.txt' does not exist.\n
Please enter the file name again: \n
double_input1.txtENTER
Total: -5,748.583\n
Average: -57.486\n
Step by stepSolved in 4 steps with 6 images
- In Java. This program asks the user to enter 5 numbers, storing them in an array of ints. Then the program outputs the smallest of those numbers and makes a Point object store the array's first two numbers as its coordinates. Finally, the program inputs the user's last name and outputs "Hello Mx." followed by their last initial. You can see sample output at the end of this file. import java.util.Scanner;import java.awt.Point; class Main{ static Scanner keyIn = new Scanner(System.in); public static void main(String[] args) { int[] nums; String lastName; char lastInitial; Point myPoint = new Point(); System.out.println("Please enter 5 numbers:"); nums = inputNums(5); outputMin(nums); changePoint(myPoint, nums); System.out.println("The first two numbers are now stored in this object:"); System.out.println(myPoint); // DO NOT CHANGE THE ABOVE CODE // PLEASE WRITE THE MISSING CODE HERE // to input the last name and output // the initial. }...arrow_forwardJava Questions - (Has 2 Parts). Based on each code, which answer out of the choices "A,B,C,D,E" is correct. Each question has one correct answer. Thank you. Part 1 - 3. Assume that "cal" is an instance of the java.util.Calendar class, which can return the current time of this Calendar in Milliseconds? A. System.out.println(cal.getTime());B. System.out.println(cal.getTimeInMillis());C. System.out.println(cal.getMillis());D. System.out.println(cal.getMillisTime());E. System.out.println(cal.getTimeMillis()); Part 2 - 4. Assume that "cal" is an instance of the java.util.Calendar class, which can set the month to February? A. cal.set(Calendar.MONTH, 1);B. cal.set(Calendar.MONTH, 2);C. cal.set(Calendar.MONTH, 3);D. cal.set(Calendar.MONTH, Feb);E. cal.set(Calendar.MONTH, February);arrow_forwardWrite a Java program ( use ComputerAverage.Java as an example) that should implement an interactive dialog that provides user with information about the procedures and asks user for information. Create a new folder Hw2_Campbell which includes the following files assignment report file:Report_Area_Circumference.doc program’s source file: Area_Circumference.Java Program’s bytecode file: Area_Curcumference.arrow_forward
- Java Program Fix this Rock, Paper and scissor program so I can upload it to Hypergrade and it can pass all the test cases. Here is the program, please fix thses program when I upload it to Hypergrade it does not pass the test cases and I can input any seeds as a command line. Also I do not need any thanks for playing or goodbye in the program: import java.util.Random; import java.util.Scanner; public class RockPaperScissors { public static void main(String[] args) { if (args.length != 1) { System.out.println("Please provide a seed as a command line argument."); return; } long seed = Long.parseLong(args[0]); Random random = new Random(seed); Scanner scanner = new Scanner(System.in); System.out.println("Enter 1 for rock, 2 for paper, and 3 for scissors."); do { int computerChoice = random.nextInt(3) + 1; // Fix computer choice range. int userChoice =...arrow_forwardPlease help how would incorporate what is asked below into the java program below. Please read the quest carefully. I have posted both the description of what to do and the output that my program bring out which is a ceos full name, there company, salary and tax owed java program is below import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class Demo{ //Method to calculate the tax static public double calcTax(double salary , double taxRate){ double taxOwed = 0; //Calclate and return the tax taxOwed = (salary * taxRate) / 100; //return the value return taxOwed; } //Main method public static void main(String[] args) throws IOException{ //Create three array to add the data ArrayList<Double> salary = new ArrayList<Double>(); ArrayList<String> name = new...arrow_forwardWrite a program that takes a first name as the input, and outputs a welcome message to that name. Ex: If the input is: Pat the output is: Hey Pat! Welcome to zyBooks! 512334.3517088.qx3zqy7 LAB ACTIVITY 1 import java.util.Scanner; 3 public class LabProgram { N&600 a 2 4 5 7 8 9 10 11 } 12 } 1123 2.29.1: LAB: Welcome message 13 public static void main(String[] args) { Scanner scnr = new Scanner(System.in); String userName; userName = scnr.next(); /* Type your code here. */ LabProgram.java Load defaarrow_forward
- Java Write a method named sumInts that can take a variable number of int arguments (see Section 7.9) and return the sum of these arguments. The ints to be summed up must be entered as command line arguments. Command line arguments can be simulated in Eclipse. Watch the video. In the main method, display the ints that were entered on the command line. Then execute sumInts and display the sum it returns.TWO SAMPLE OUTPUTS Passing [1, 2, 3, 4, 5]Sum is 15 Passing [10, 20, 30]Sum is 60arrow_forwardI need help with a Java program described below: import java.util.Scanner;import java.io.FileInputStream;import java.io.IOException; public class LabProgram { public static void main(String[] args) throws IOException { Scanner scnr = new Scanner(System.in); /* Type your code here. */ }}arrow_forwardUSING JAVAarrow_forward
- Please help how do I make the code show on the black screen instead of a txt.file. By the way I have already created a txt.file in this java compiler called Data.txtarrow_forwardI need help write a second constructor in java code. It's described in the image below.arrow_forwardJava Proram ASAP Please improve and adjust the program which is down below with the futher moddifications because it does not pass the test cases in Hypergrade. Please remove /n from the program and for test case 4 after this line: Please re-enter the file name or type QUIT to exit:\n quitENTER there needs to be nothing. import java.io.*;import java.util.Scanner;public class ConvertText { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); System.out.println("Please enter the file name or type QUIT to exit:"); while (true) { String input = sc.next(); if (input.compareTo("QUIT") == 0) { break; } else { String filePath = new File("").getAbsolutePath(); filePath = filePath.concat("/"); filePath = filePath.concat(input); File file = new File(filePath); if (file.exists() && !file.isDirectory()) {...arrow_forward
- Text book imageDatabase System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationText book imageStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONText book imageDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- Text book imageC How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONText book imageDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningText book imageProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education