Advertisement
brilliant_moves

TestScores.java

Apr 23rd, 2014
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.92 KB | None | 0 0
  1. /*
  2.  
  3. Asked on Y!A on 23.04.2014:
  4.  
  5. Write a java program that reads the data from a file and prints each student name and the percentage
  6.  they made in the exam.?
  7. The text file “marks.txt” stores the total mark for an exam on the first line and student's names
  8. and test scores on the following lines as shown below (the number of student data stored in the
  9. file is not known.) Write a java program that reads the data from the file and prints each student
  10. name and the percentage they made in the exam.
  11.  
  12. marks.txt
  13. 125
  14. Mary 102
  15. Josh 88
  16.  
  17. */
  18.  
  19. import java.io.*;
  20. import java.util.Scanner;
  21. import java.util.NoSuchElementException;
  22.  
  23. public class TestScores {
  24.  
  25.     /**
  26.     *   Program:    TestScores.java
  27.     *   Purpose:    Read data from file, display names and scores as percentages.
  28.     *   Creator:    Chris Clarke
  29.     *   Created:    23.04.2014
  30.     *   Notes:      Search Amazon for:
  31.     *           "50 Java Program Source Codes" and "50 More Java Source Codes"
  32.     *           available in Kindle e-book format and in paperback.
  33.     */
  34.  
  35.     public static void main(String[] args) {
  36.         File f;
  37.         double totalMark = 0.0f;
  38.         int testScore = 0;
  39.         double percent = 0.0f;
  40.         Scanner fileScan;
  41.         String name = "";
  42.         try {
  43.             f = new File("marks.txt");
  44.             fileScan = new Scanner(f);
  45.             if (fileScan.hasNext()) {
  46.                 totalMark = Double.parseDouble( fileScan.nextLine());
  47.                 System.out.println( (int)(totalMark));
  48.             } // end if
  49.  
  50.             while (fileScan.hasNext()) {
  51.                 name = fileScan.next();
  52.                 testScore = Integer.parseInt( fileScan.next());
  53.                 percent = (testScore / totalMark) * 100.0;
  54.                 System.out.printf("%s %5.1f percent%n", name, percent);
  55.             } // end while
  56.         }
  57.         catch (FileNotFoundException e) {
  58.             System.out.println("File Not Found!");
  59.         }
  60.         catch (NoSuchElementException e) {
  61.             System.out.println("Error: missing data!");
  62.         }
  63.         catch (NumberFormatException e) {
  64.             System.out.println("Not a number!");
  65.         } // end try..catch
  66.     } // end main()
  67.  
  68. } // end class TestScores
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement