So my assignment is
1)To create file and output ten numbers to said file.
2)To read as input the numbers in the file and output the # of numbers, average, and total sum
3)Output results to the same file
My problem is a runtime error, the compiler doesn't catch it.
I'm not really sure what to do. We're told to throw all exceptions for now because we havent learned how to deal with them. I have throws IOException in the main method header, but I have a problem with the program. When I try to run it the error code is
Exception in thread "main" java.lang.IllegalArgumentException: Malformed pattern "##.#0"
at java.text.DecimalFormat.applyPattern(DecimalFormat .java:2610)
at java.text.DecimalFormat.<init>(DecimalFormat.java: 435)
at QudratullahMommandi_3_4.main(QudratullahMommandi_3 _4.java:25)
I don't see how the pattern is malformed, but debugging language is straight up esoteric to me at this point, am I using the text formatting util wrong or something? Also any help is appreciated, this is my second post in two days so hopefully this isnt considered spamming the forum, and a ty ahead of time to anyone who takes the time to read this.
import java.io.*; import java.util.Scanner; import java.text.DecimalFormat; public class QudratullahMommandi_3_4 { public static void main (String[]args) throws IOException { int numberOfNumbers = 0; double totalSum = 0; double average; //Formatting object to format average and # of nums DecimalFormat formatter = new DecimalFormat("##.#0"); // Creating s file and outputting numbers to it PrintWriter newOutput = new PrintWriter("QudratMommandi_S_04_Output.txt"); newOutput.println("10.5"); newOutput.println("10 55"); newOutput.println("7.1"); newOutput.println("55.5"); newOutput.println("21.5 22.1"); newOutput.println("12.5 78.9"); newOutput.println("77.7"); // Closing the file so the numbers are saved newOutput.close(); //Creating a file object refering to the file //Creating a scanner object refering the file object for input File inputSource = new File("QudratMommandi_s_04_Output.txt"); Scanner inputFile = new Scanner(inputSource); while (inputFile.hasNext()) { //Tally of the number of input numbers, used to calculate average later on numberOfNumbers++; //reading input and saving it to variable double num = inputFile.nextDouble(); //Total sum holds all the numbers read added subsequently to one another totalSum += num; } //closing file to save data inputFile.close(); //Calculating average average = totalSum/numberOfNumbers; //opening file for output FileWriter fwriter = new FileWriter("QudratMommandi_S_04_Output.txt", true); PrintWriter finalStage = new PrintWriter(fwriter); //Outputting new data into file finalStage.println(numberOfNumbers); finalStage.println(formatter.format(totalSum)); finalStage.println(formatter.format(average)); System.out.println(numberOfNumbers); System.out.println(totalSum); System.out.println(average); System.exit(0); } }