/*
* Write a program which prompts the user for the number of credits earned and the number of credits needed to graduate.
* Use two input dialog windows as prompts.
* The input data should be integers.
* The program calculates the percentage of completion.
* Use a dialog window for output and format the percentage one place.
* An icon is needed for the output.
*/
package com.betsalel.labAssignments.LabAssign1;
import java.text.DecimalFormat;
import java.util.Scanner;
import javax.swing.*;
/**
*
* @author Betsalel Williamson
* 01.23.2012
*/
public class LabAssign1 {
private int creditsEarned, creditsNeeded;
private boolean displayUI;
//LABASSIGN OBJECT TO HOLD USER INPUT
public LabAssign1() {
creditsEarned = 0;
creditsNeeded = 0;
displayUI = true;
}
public LabAssign1(boolean dUI) {
creditsEarned = 0;
creditsNeeded = 0;
displayUI = dUI;
}
public LabAssign1(int cE, int cN, boolean dUI) {
creditsEarned = cE;
creditsNeeded = cN;
displayUI = dUI;
}
public void setCreditsEarned(int cE) {
creditsEarned = cE;
}
public void setCreditsEarned() {
String userInput;
if (this.getDisplayUIStatus()) {
do {
userInput = JOptionPane.showInputDialog(null,
"Enter the number of credits earned",
"Credits Earned",
JOptionPane.DEFAULT_OPTION);
} while (!isOfType("int", userInput));
this.setCreditsEarned(Integer.parseInt(userInput));
} else {
do {
Scanner readInput = new Scanner(System.in);
System.out.println("Enter the number of credits earned");
userInput = readInput.nextLine();
} while (!isOfType("int", userInput));
this.setCreditsEarned(Integer.parseInt(userInput));
}
}
public void setCreditsNeeded(int cN) {
creditsNeeded = cN;
}
public void setCreditsNeeded() {
String userInput;
if (this.getDisplayUIStatus()) {
do {
userInput = JOptionPane.showInputDialog(null,
"Enter the number of credits needed to graduate",
"Credits Needed",
JOptionPane.DEFAULT_OPTION);
} while (!isOfType("int", userInput));
this.setCreditsNeeded(Integer.parseInt(userInput));
} else {
do {
Scanner readInput = new Scanner(System.in);
System.out.println("Enter the number of credits needed to graduate");
userInput = readInput.nextLine();
} while (!isOfType("int", userInput));
this.setCreditsNeeded(Integer.parseInt(userInput));
}
}
public boolean getDisplayUIStatus(){
return displayUI;
}
public int getCreditsEarned() {
return creditsEarned;
}
public int getCreditsNeeded() {
return creditsNeeded;
}
static final double USER_INPUT_ERROR = -1;
public double calculatePercentage() {
double numerator = this.getCreditsEarned(), denominator = this.getCreditsNeeded();
//ROBUSTNESS CODE TO MAKE SURE THAT...
//THERE ARE NO DIVIDE BY ZERO ERRORS
if (denominator == 0) {
System.err.println("Denominator is 0");
return USER_INPUT_ERROR;
}
//THAT YOU CAN'T GET MORE THAN 100
if (numerator > denominator) {
System.err.println("Denominator is smaller than numerator");
return USER_INPUT_ERROR;
}
//AND NEGATIVE CREDITS AREN'T ALLOWED
if (numerator < 0 || denominator < 0) {
System.err.println("Result is negative");
return USER_INPUT_ERROR;
}
double percentComplete;
return percentComplete = ((numerator) / (denominator)) * 100;
//MULTIPLIED BY 100 TO RETURN A PERCENTAGE VALUE OUT OF 100.00
}
public double getPercentComplete() {
DecimalFormat formatToOnePlace = new DecimalFormat("##.#");
if (this.getDisplayUIStatus()) {
ImageIcon printIcon = new ImageIcon(LabAssign1.class.getResource("Print.png"));
JOptionPane.showMessageDialog(null, "You are "
+ formatToOnePlace.format(this.calculatePercentage())
+ "% complete for your degree",
"Percent Complete",
JOptionPane.INFORMATION_MESSAGE,
printIcon);
} else {
System.out.println("You are "
+ formatToOnePlace.format(this.calculatePercentage())
+ "% complete for your degree");
}
return this.calculatePercentage();
}
public static void main(String[] args) {
LabAssign1 myCollegeStatus = new LabAssign1();
do {
//DO WHILE USER HASN'T ENTERED A USEABLE INPUT
myCollegeStatus.setCreditsEarned();
myCollegeStatus.setCreditsNeeded();
} while (myCollegeStatus.calculatePercentage() == USER_INPUT_ERROR);
myCollegeStatus.getPercentComplete();
System.exit(0);
}
/**************************ERROR HANDLING CODE****************************/
/*DOES NOT ACCOUNT FOR MULTIPLE '-' OR '.'*/
//could handle that by only allowing index zero to have a -, but for . it would require a boolean to count for only one
//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.
public static boolean checkCurrentStringForChar(String s,
boolean canHaveMinus, boolean canHaveDecimal) {
boolean isValidChar = true;
boolean hasNumber = false, hadMinus = false, hasPeriod = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// System.out.print("Index " + i + ": ");
//if the type canHaveDecimal it can have minus as well
if (canHaveDecimal) {
//reads if is not a number or period or minus symbol
if (!(('0' <= c && c <= '9') || c == '.' || c == '-')) {
// System.out.println("Invalid char: " + c);
isValidChar = false;
} else {
// System.out.println("Valid char: " + c);
}
} else if (canHaveMinus) {
if (!(('0' <= c && c <= '9') || c == '-')) {
// System.out.println("Invalid char: " + c);
isValidChar = false;
} else {
// System.out.println("Valid char: " + c);
}
} else {
if (!('0' <= c && c <= '9')) {
// System.out.println("Invalid char: " + c);
isValidChar = false;
} else {
// System.out.println("Valid char: " + c);
}
}
}
return isValidChar;
}
public static boolean isOfType(String typeWanted, String... inputString) {
String[] primitiveDataTypes = {"boolean",
"byte",
"short",
"int",
"long",
"float",
"double",
"char"};
boolean stringIsOfType = true;
//assume the result is good unless error is found
//variable is used in for loop
/******************************INITIAL CHECK*********************************/
//makes sure type field is not empty
if (typeWanted.isEmpty()) {
System.out.println(
"Invalid type. Please choose:\n"
+ "\"boolean\","
+ "\"byte\","
+ "\"short\","
+ "\"int\","
+ "\"long\","
+ "\"float\","
+ "\"double\", or "
+ "\"char\"");
System.out.println("...");
System.out.println("Ready for the next input...\n");
return false;
} //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
else {
System.out.println("\nChecking string(s) for compatibility with type " + typeWanted + ".\n");
}
/****************************************************************************/
//go thorugh strings and find the type to check for
int stringCounter = 0;
for (String currentString : inputString) {
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
if (currentString.isEmpty()) {//the currentString is no longer valid and is not checked
System.out.println("Invalid: Empty String");
isCurrentStringValid = false;
} else {
System.out.println("Reading field #"
+ (stringCounter + 1)
+ ": "
+ "\"" + currentString + "\"");
/****************************************************************************/
/*"typeBoolean"*/
if (primitiveDataTypes[0].equals(typeWanted)) {
//incomplete, need better understanding of how JAVA handles boolean to string conversions
} /*"typeByte"*/ else if (primitiveDataTypes[1].equals(typeWanted)) {
if (checkCurrentStringForChar(currentString, false, false)) {
if (Double.parseDouble(currentString) > Byte.MAX_VALUE
|| Double.parseDouble(currentString) < Byte.MIN_VALUE) {
System.out.println("Wrong size for byte: " + currentString);
isCurrentStringValid = false;
}
} else {
isCurrentStringValid = false;
}
} /*"typeShort"*/ else if (primitiveDataTypes[2].equals(typeWanted)) {
if (checkCurrentStringForChar(currentString, false, false)) {
if (Double.parseDouble(currentString) > Short.MAX_VALUE
|| Double.parseDouble(currentString) < Short.MIN_VALUE) {
System.out.println("Wrong size for short: " + currentString);
isCurrentStringValid = false;
}
} else {
isCurrentStringValid = false;
}
} /*"typeInt"*/ else if (primitiveDataTypes[3].equals(typeWanted)) {
if (checkCurrentStringForChar(currentString, true, false)) {
if (Double.parseDouble(currentString) > Integer.MAX_VALUE
|| Double.parseDouble(currentString) < Integer.MIN_VALUE) {
System.out.println("Wrong size for int: " + currentString);
isCurrentStringValid = false;
}
} else {
isCurrentStringValid = false;
}
} /*"typeLong"*/ else if (primitiveDataTypes[4].equals(typeWanted)) {
if (checkCurrentStringForChar(currentString, true, false)) {
if (Double.parseDouble(currentString) > Long.MAX_VALUE
|| Double.parseDouble(currentString) < Long.MIN_VALUE) {
System.out.println("Wrong size for long: " + currentString);
isCurrentStringValid = false;
}
} else {
isCurrentStringValid = false;
}
} /*"typeFloat"*/ else if (primitiveDataTypes[5].equals(typeWanted)) {
if (checkCurrentStringForChar(currentString, true, true))
; else {
isCurrentStringValid = false;
}
} /*"typeDouble"*/ else if (primitiveDataTypes[6].equals(typeWanted)) {
if (checkCurrentStringForChar(currentString, true, true))
; else {
isCurrentStringValid = false;
}
} /*"typeChar"*/ else if (primitiveDataTypes[7].equals(typeWanted)) {
for (int i = 0; i < currentString.length(); i++) {
char c = currentString.charAt(i);
}
} /*type not found*/ else {
System.out.println("You tried to test type: " + typeWanted);
System.out.println("That is not a proper type, edit your code!");
return false;//exit error checking method
}
}
System.out.println("...");
if (isCurrentStringValid == false) {
System.out.println("Result field #" + (stringCounter + 1) + ": Invalid input");
System.out.println("...");
stringIsOfType = false;//this string is not of type wanted and is unsafe for use with string parse methods of type chosen
} else {
System.out.println("Result field #" + (stringCounter + 1) + ": Valid input.");
System.out.println("...");
}
stringCounter++;//increment to show next string
isCurrentStringValid = true;//reset the inner boolean, check for next string
}//END OF for( s : inputString )
if (stringIsOfType == false) {
System.out.println("Final Result: Invalid input.");
System.out.println("...");
System.out.println("Ready for the next input...\n");
return false;
}
//else
System.out.println("Final Result: Vaild input.");
System.out.println("...");
System.out.println("Ready for the next input...\n");
return true;
}//END OF isOfType error checking code
}