Advertisement
Conner_36

Calculate Percentage

Jan 24th, 2012
397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.58 KB | None | 0 0
  1. /*
  2.  * Write a program which prompts the user for the number of credits earned and the number of credits needed to graduate.
  3.  * Use two input dialog windows as prompts.
  4.  * The input data should be integers.
  5.  * The program calculates the percentage of completion.
  6.  * Use a dialog window for output and format the percentage one place.
  7.  * An icon is needed for the output.
  8.  */
  9. package com.betsalel.labAssignments.LabAssign1;
  10.  
  11. import java.text.DecimalFormat;
  12. import java.util.Scanner;
  13. import javax.swing.*;
  14.  
  15. /**
  16.  *
  17.  * @author Betsalel Williamson
  18.  * 01.23.2012
  19.  */
  20. public class LabAssign1 {
  21.  
  22.    private int creditsEarned, creditsNeeded;
  23.    private boolean displayUI;
  24.  
  25.    //LABASSIGN OBJECT TO HOLD USER INPUT
  26.    public LabAssign1() {
  27.       creditsEarned = 0;
  28.       creditsNeeded = 0;
  29.       displayUI = true;
  30.    }
  31.  
  32.    public LabAssign1(boolean dUI) {
  33.       creditsEarned = 0;
  34.       creditsNeeded = 0;
  35.       displayUI = dUI;
  36.    }
  37.  
  38.    public LabAssign1(int cE, int cN, boolean dUI) {
  39.       creditsEarned = cE;
  40.       creditsNeeded = cN;
  41.       displayUI = dUI;
  42.    }
  43.  
  44.    public void setCreditsEarned(int cE) {
  45.       creditsEarned = cE;
  46.  
  47.    }
  48.  
  49.    public void setCreditsEarned() {
  50.       String userInput;
  51.  
  52.       if (this.getDisplayUIStatus()) {
  53.          do {
  54.             userInput = JOptionPane.showInputDialog(null,
  55.                     "Enter the number of credits earned",
  56.                     "Credits Earned",
  57.                     JOptionPane.DEFAULT_OPTION);
  58.          } while (!isOfType("int", userInput));
  59.  
  60.          this.setCreditsEarned(Integer.parseInt(userInput));
  61.  
  62.       } else {
  63.          do {
  64.             Scanner readInput = new Scanner(System.in);
  65.  
  66.             System.out.println("Enter the number of credits earned");
  67.  
  68.             userInput = readInput.nextLine();
  69.  
  70.          } while (!isOfType("int", userInput));
  71.  
  72.          this.setCreditsEarned(Integer.parseInt(userInput));
  73.       }
  74.    }
  75.  
  76.    public void setCreditsNeeded(int cN) {
  77.       creditsNeeded = cN;
  78.    }
  79.  
  80.    public void setCreditsNeeded() {
  81.       String userInput;
  82.  
  83.       if (this.getDisplayUIStatus()) {
  84.          do {
  85.             userInput = JOptionPane.showInputDialog(null,
  86.                     "Enter the number of credits needed to graduate",
  87.                     "Credits Needed",
  88.                     JOptionPane.DEFAULT_OPTION);
  89.          } while (!isOfType("int", userInput));
  90.  
  91.          this.setCreditsNeeded(Integer.parseInt(userInput));
  92.       } else {
  93.          do {
  94.             Scanner readInput = new Scanner(System.in);
  95.  
  96.             System.out.println("Enter the number of credits needed to graduate");
  97.  
  98.             userInput = readInput.nextLine();
  99.  
  100.          } while (!isOfType("int", userInput));
  101.          this.setCreditsNeeded(Integer.parseInt(userInput));
  102.       }
  103.    }
  104.  
  105.    public boolean getDisplayUIStatus(){
  106.       return displayUI;
  107.    }
  108.    public int getCreditsEarned() {
  109.       return creditsEarned;
  110.    }
  111.  
  112.    public int getCreditsNeeded() {
  113.       return creditsNeeded;
  114.    }
  115.  
  116.    static final double USER_INPUT_ERROR = -1;
  117.    public double calculatePercentage() {
  118.  
  119.       double numerator = this.getCreditsEarned(), denominator = this.getCreditsNeeded();
  120.  
  121.       //ROBUSTNESS CODE TO MAKE SURE THAT...
  122.       //THERE ARE NO DIVIDE BY ZERO ERRORS
  123.       if (denominator == 0) {
  124.          System.err.println("Denominator is 0");
  125.          return USER_INPUT_ERROR;
  126.       }
  127.       //THAT YOU CAN'T GET MORE THAN 100
  128.       if (numerator > denominator) {
  129.          System.err.println("Denominator is smaller than numerator");
  130.          return USER_INPUT_ERROR;
  131.       }
  132.       //AND NEGATIVE CREDITS AREN'T ALLOWED
  133.       if (numerator < 0 || denominator < 0) {
  134.          System.err.println("Result is negative");
  135.          return USER_INPUT_ERROR;
  136.       }
  137.  
  138.       double percentComplete;
  139.  
  140.       return percentComplete = ((numerator) / (denominator)) * 100;
  141.       //MULTIPLIED BY 100 TO RETURN A PERCENTAGE VALUE OUT OF 100.00
  142.    }
  143.  
  144.    public double getPercentComplete() {
  145.       DecimalFormat formatToOnePlace = new DecimalFormat("##.#");
  146.       if (this.getDisplayUIStatus()) {
  147.          ImageIcon printIcon = new ImageIcon(LabAssign1.class.getResource("Print.png"));
  148.  
  149.          JOptionPane.showMessageDialog(null, "You are "
  150.                  + formatToOnePlace.format(this.calculatePercentage())
  151.                  + "% complete for your degree",
  152.                  "Percent Complete",
  153.                  JOptionPane.INFORMATION_MESSAGE,
  154.                  printIcon);
  155.       } else {
  156.          System.out.println("You are "
  157.                  + formatToOnePlace.format(this.calculatePercentage())
  158.                  + "% complete for your degree");
  159.       }
  160.       return this.calculatePercentage();
  161.    }
  162.  
  163.    public static void main(String[] args) {
  164.       LabAssign1 myCollegeStatus = new LabAssign1();
  165.  
  166.       do {
  167.          //DO WHILE USER HASN'T ENTERED A USEABLE INPUT
  168.          myCollegeStatus.setCreditsEarned();
  169.  
  170.          myCollegeStatus.setCreditsNeeded();
  171.  
  172.       } while (myCollegeStatus.calculatePercentage() == USER_INPUT_ERROR);
  173.  
  174.       myCollegeStatus.getPercentComplete();
  175.  
  176.       System.exit(0);
  177.    }
  178.  
  179.    /**************************ERROR HANDLING CODE****************************/
  180.    /*DOES NOT ACCOUNT FOR MULTIPLE '-' OR '.'*/
  181.    //could handle that by only allowing index zero to have a -, but for . it would require a boolean to count for only one
  182.    //I need a boolean to handle is there a num, a minus, or period. Without it just having a period or minus can throw an exception error.
  183.    public static boolean checkCurrentStringForChar(String s,
  184.            boolean canHaveMinus, boolean canHaveDecimal) {
  185.  
  186.       boolean isValidChar = true;
  187.       boolean hasNumber = false, hadMinus = false, hasPeriod = false;
  188.  
  189.       for (int i = 0; i < s.length(); i++) {
  190.  
  191.          char c = s.charAt(i);
  192.  
  193. //         System.out.print("Index " + i + ": ");
  194.  
  195.          //if the type canHaveDecimal it can have minus as well
  196.          if (canHaveDecimal) {
  197.             //reads if is not a number or period or minus symbol
  198.             if (!(('0' <= c && c <= '9') || c == '.' || c == '-')) {
  199. //               System.out.println("Invalid char: " + c);
  200.                isValidChar = false;
  201.             } else {
  202. //               System.out.println("Valid char: " + c);
  203.             }
  204.          } else if (canHaveMinus) {
  205.             if (!(('0' <= c && c <= '9') || c == '-')) {
  206. //               System.out.println("Invalid char: " + c);
  207.                isValidChar = false;
  208.             } else {
  209. //               System.out.println("Valid char: " + c);
  210.             }
  211.          } else {
  212.             if (!('0' <= c && c <= '9')) {
  213. //               System.out.println("Invalid char: " + c);
  214.                isValidChar = false;
  215.             } else {
  216. //               System.out.println("Valid char: " + c);
  217.             }
  218.          }
  219.       }
  220.       return isValidChar;
  221.    }
  222.  
  223.    public static boolean isOfType(String typeWanted, String... inputString) {
  224.       String[] primitiveDataTypes = {"boolean",
  225.          "byte",
  226.          "short",
  227.          "int",
  228.          "long",
  229.          "float",
  230.          "double",
  231.          "char"};
  232.  
  233.       boolean stringIsOfType = true;
  234.       //assume the result is good unless error is found
  235.       //variable is used in for loop
  236.  
  237.       /******************************INITIAL CHECK*********************************/
  238. //makes sure type field is not empty
  239.       if (typeWanted.isEmpty()) {
  240.          System.out.println(
  241.                  "Invalid type. Please choose:\n"
  242.                  + "\"boolean\","
  243.                  + "\"byte\","
  244.                  + "\"short\","
  245.                  + "\"int\","
  246.                  + "\"long\","
  247.                  + "\"float\","
  248.                  + "\"double\", or "
  249.                  + "\"char\"");
  250.          System.out.println("...");
  251.          System.out.println("Ready for the next input...\n");
  252.          return false;
  253.       } //if a type choosen is not listed, the for loop will find it out and display what you entered, please choose the types listed above until the code become more robust
  254.       else {
  255.          System.out.println("\nChecking string(s) for compatibility with type " + typeWanted + ".\n");
  256.       }
  257.  
  258.       /****************************************************************************/
  259.       //go thorugh strings and find the type to check for
  260.       int stringCounter = 0;
  261.       for (String currentString : inputString) {
  262.          boolean isCurrentStringValid = true;//initialize the boolean as true, the enhanced FOR loop doesn't allow for initial variables and incrementers along with the string incrementer
  263.  
  264.          if (currentString.isEmpty()) {//the currentString is no longer valid and is not checked
  265.             System.out.println("Invalid: Empty String");
  266.             isCurrentStringValid = false;
  267.          } else {
  268.  
  269.             System.out.println("Reading field #"
  270.                     + (stringCounter + 1)
  271.                     + ": "
  272.                     + "\"" + currentString + "\"");
  273.  
  274.             /****************************************************************************/
  275.             /*"typeBoolean"*/
  276.             if (primitiveDataTypes[0].equals(typeWanted)) {
  277.                //incomplete, need better understanding of how JAVA handles boolean to string conversions
  278.             } /*"typeByte"*/ else if (primitiveDataTypes[1].equals(typeWanted)) {
  279.                if (checkCurrentStringForChar(currentString, false, false)) {
  280.                   if (Double.parseDouble(currentString) > Byte.MAX_VALUE
  281.                           || Double.parseDouble(currentString) < Byte.MIN_VALUE) {
  282.                      System.out.println("Wrong size for byte: " + currentString);
  283.                      isCurrentStringValid = false;
  284.                   }
  285.                } else {
  286.                   isCurrentStringValid = false;
  287.                }
  288.             } /*"typeShort"*/ else if (primitiveDataTypes[2].equals(typeWanted)) {
  289.                if (checkCurrentStringForChar(currentString, false, false)) {
  290.                   if (Double.parseDouble(currentString) > Short.MAX_VALUE
  291.                           || Double.parseDouble(currentString) < Short.MIN_VALUE) {
  292.                      System.out.println("Wrong size for short: " + currentString);
  293.                      isCurrentStringValid = false;
  294.                   }
  295.                } else {
  296.                   isCurrentStringValid = false;
  297.                }
  298.             } /*"typeInt"*/ else if (primitiveDataTypes[3].equals(typeWanted)) {
  299.                if (checkCurrentStringForChar(currentString, true, false)) {
  300.                   if (Double.parseDouble(currentString) > Integer.MAX_VALUE
  301.                           || Double.parseDouble(currentString) < Integer.MIN_VALUE) {
  302.                      System.out.println("Wrong size for int: " + currentString);
  303.                      isCurrentStringValid = false;
  304.                   }
  305.                } else {
  306.                   isCurrentStringValid = false;
  307.                }
  308.             } /*"typeLong"*/ else if (primitiveDataTypes[4].equals(typeWanted)) {
  309.                if (checkCurrentStringForChar(currentString, true, false)) {
  310.                   if (Double.parseDouble(currentString) > Long.MAX_VALUE
  311.                           || Double.parseDouble(currentString) < Long.MIN_VALUE) {
  312.                      System.out.println("Wrong size for long: " + currentString);
  313.                      isCurrentStringValid = false;
  314.                   }
  315.                } else {
  316.                   isCurrentStringValid = false;
  317.                }
  318.             } /*"typeFloat"*/ else if (primitiveDataTypes[5].equals(typeWanted)) {
  319.                if (checkCurrentStringForChar(currentString, true, true))
  320.                   ; else {
  321.                   isCurrentStringValid = false;
  322.                }
  323.  
  324.             } /*"typeDouble"*/ else if (primitiveDataTypes[6].equals(typeWanted)) {
  325.                if (checkCurrentStringForChar(currentString, true, true))
  326.                   ; else {
  327.                   isCurrentStringValid = false;
  328.                }
  329.  
  330.             } /*"typeChar"*/ else if (primitiveDataTypes[7].equals(typeWanted)) {
  331.                for (int i = 0; i < currentString.length(); i++) {
  332.                   char c = currentString.charAt(i);
  333.                }
  334.             } /*type not found*/ else {
  335.                System.out.println("You tried to test type: " + typeWanted);
  336.                System.out.println("That is not a proper type, edit your code!");
  337.                return false;//exit error checking method
  338.             }
  339.          }
  340.  
  341.          System.out.println("...");
  342.  
  343.          if (isCurrentStringValid == false) {
  344.             System.out.println("Result field #" + (stringCounter + 1) + ": Invalid input");
  345.             System.out.println("...");
  346.             stringIsOfType = false;//this string is not of type wanted and is unsafe for use with string parse methods of type chosen
  347.          } else {
  348.             System.out.println("Result field #" + (stringCounter + 1) + ": Valid input.");
  349.             System.out.println("...");
  350.          }
  351.  
  352.          stringCounter++;//increment to show next string
  353.          isCurrentStringValid = true;//reset the inner boolean, check for next string
  354.       }//END OF for( s : inputString )
  355.  
  356.       if (stringIsOfType == false) {
  357.          System.out.println("Final Result: Invalid input.");
  358.          System.out.println("...");
  359.          System.out.println("Ready for the next input...\n");
  360.          return false;
  361.       }
  362.  
  363.       //else
  364.       System.out.println("Final Result: Vaild input.");
  365.       System.out.println("...");
  366.       System.out.println("Ready for the next input...\n");
  367.       return true;
  368.    }//END OF isOfType error checking code
  369. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement