Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Asked on Y!A on 23.04.2014:
- Write a java program that reads the data from a file and prints each student name and the percentage
- they made in the exam.?
- The text file “marks.txt” stores the total mark for an exam on the first line and student's names
- and test scores on the following lines as shown below (the number of student data stored in the
- file is not known.) Write a java program that reads the data from the file and prints each student
- name and the percentage they made in the exam.
- marks.txt
- 125
- Mary 102
- Josh 88
- */
- import java.io.*;
- import java.util.Scanner;
- import java.util.NoSuchElementException;
- public class TestScores {
- /**
- * Program: TestScores.java
- * Purpose: Read data from file, display names and scores as percentages.
- * Creator: Chris Clarke
- * Created: 23.04.2014
- * Notes: Search Amazon for:
- * "50 Java Program Source Codes" and "50 More Java Source Codes"
- * available in Kindle e-book format and in paperback.
- */
- public static void main(String[] args) {
- File f;
- double totalMark = 0.0f;
- int testScore = 0;
- double percent = 0.0f;
- Scanner fileScan;
- String name = "";
- try {
- f = new File("marks.txt");
- fileScan = new Scanner(f);
- if (fileScan.hasNext()) {
- totalMark = Double.parseDouble( fileScan.nextLine());
- System.out.println( (int)(totalMark));
- } // end if
- while (fileScan.hasNext()) {
- name = fileScan.next();
- testScore = Integer.parseInt( fileScan.next());
- percent = (testScore / totalMark) * 100.0;
- System.out.printf("%s %5.1f percent%n", name, percent);
- } // end while
- }
- catch (FileNotFoundException e) {
- System.out.println("File Not Found!");
- }
- catch (NoSuchElementException e) {
- System.out.println("Error: missing data!");
- }
- catch (NumberFormatException e) {
- System.out.println("Not a number!");
- } // end try..catch
- } // end main()
- } // end class TestScores
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement