If-else statements made my program stop immediately -- Java - java

I'm just going to post what I've got so far in a program that is supposed to do the following:
- Calculate BAC (blood alcohol content) based on inputs given by the user and determine, with the various inputs, whether or not they would get a DUI (be over the limit based on inputs given).
So here's my code:
import java.util.*;
public class Proj2_Mazzone
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
String gender;
int D, W, H, age;
double ratio, limit, alcAbsorbed, alcMetabolized, BAC;
...
//BAC is calculated here, based on given input
//Make 4 diff scenarios using && with if statements...
//So f21, fnot21, m21, mnot21
System.out.print("Enter M if you're a male, or F if you're a female: ");
gender = scan.nextLine();
//males over 21
if(gender.equalsIgnoreCase("m") && age > 21){
ratio = .73;
limit = .08;
alcAbsorbed = (3.701 * D) / (W * ratio);
alcMetabolized = .015 * H;
BAC = alcAbsorbed - alcMetabolized;
if(BAC >= limit){
System.out.println("You're over the limit!");
System.out.println("Your BAC is " + BAC + "!");
}
else if(BAC <= limit){
System.out.println("You're good...for now.");
System.out.println("Your BAC is " + BAC + ".");
}
}
//males under 21
if(gender.equalsIgnoreCase("m") && age < 21){
ratio = .73;
limit = .02;
alcAbsorbed = (3.701 * D) / (W * ratio);
alcMetabolized = .015 * H;
BAC = alcAbsorbed - alcMetabolized;
if(BAC >= limit){
System.out.println("You're over the limit!");
System.out.println("Your BAC is " + BAC + "!");
}
else if(BAC <= limit){
System.out.println("You're good...for now.");
System.out.println("Your BAC is " + BAC + ".");
}
}
//females over 21
if(gender.equalsIgnoreCase("f") && age > 21){
ratio = .66;
limit = .08;
alcAbsorbed = (3.701 * D) / (W * ratio);
alcMetabolized = .015 * H;
BAC = alcAbsorbed - alcMetabolized;
if(BAC >= limit){
System.out.println("You're over the limit!");
System.out.println("Your BAC is " + BAC + "!");
}
else if(BAC <= limit){
System.out.println("You're good...for now.");
System.out.println("Your BAC is " + BAC + ".");
}
}
//females under 21
if(gender.equalsIgnoreCase("f") && age < 21){
ratio = .66;
limit = .02;
alcAbsorbed = (3.701 * D) / (W * ratio);
alcMetabolized = .015 * H;
BAC = alcAbsorbed - alcMetabolized;
if(BAC >= limit){
System.out.println("You're over the limit!");
System.out.println("Your BAC is " + BAC + "!");
}
else if(BAC <= limit){
System.out.println("You're good...for now.");
System.out.println("Your BAC is " + BAC + ".");
}
}
...
It may not be the best way to do it, but any help is appreciated. Thanks in advance.

The real problem in the else if statements is that one of them may not trigger. Instead of doing an if else if statement in the if(BAC<=limit), do something like:
if (BAC >= limit) {
System.out.println("You're over the limit!");
System.out.println("Your BAC is " + BAC + "!");
} else {
System.out.println("You're good...for now.");
System.out.println("Your BAC is " + BAC + ".");
}
Also, do you ever read the age in you program?

Rather than writing same code again and again you should create one common function. That will take 2 arguments that is ratio and limit.
Apart from this all other calculations are common for all age limits and male or female.
Do your calculation in that function and simply print it
it will shorten your code and will make it more readable and understandable.

There's a logic problem: 21 year old females fall through. Your main ifs are:
if(gender.equalsIgnoreCase("f") && age > 21){
...
}
if(gender.equalsIgnoreCase("f") && age < 21){
....
}
If the age is exactly 21, neither block will be entered.

Your problem comes from the fact that your conditions are wrong for a women who is 21 year old! She's excluded from all the cases.
Also your code is hard to debug because it's hard to read.
Consider the following refactoring where I created methods to determine the values.
I went very far for a simple code like that but it's to show you that you should never copy/paste code. When you repeat code, it means that you can put it in a method that will be called several times with the right arguments.
public class StackOverflow {
// TODO define the real values!
private static final int D = 0, W = 0, H = 0;
public static void main(String[] args) {
// Get the input
Scanner scan = new Scanner(System.in);
System.out.print("Enter M if you're a male, or F if you're a female: ");
String gender = scan.nextLine();
System.out.print("Enter your age: ");
int age = Integer.valueOf(scan.nextLine());
// Get the good values
double ratio = getRatio(gender);
double bac = getBAC(ratio);
double limit = getLimit(age);
// Print the result
if (bac <= limit) {
System.out.println("You're good...for now.");
} else {
System.out.println("You're over the limit!");
}
System.out.println("Your BAC is " + bac + "!");
}
/**
* This method returns the ratio according to the gender.
*/
private static double getRatio(String gender) {
if ("m".equalsIgnoreCase(gender)) {
return .73;
} else if ("f".equalsIgnoreCase(gender)) {
return .66;
}
throw new IllegalArgumentException("Unknown gender: " + gender);
}
/**
* This method returns the BAC according to the ratio.
*/
private static double getBAC(double ratio) {
double alcAbsorbed = (3.701 * D) / (W * ratio);
double alcMetabolized = .015 * H;
return alcAbsorbed - alcMetabolized;
}
/**
* This method returns the limit according to the age.
*/
private static double getLimit(int age) {
if (age < 21) {
return .02;
} else {
return .08;
}
}
}

I would recommend to refactor this code after you've found the problem to reduce duplication. Also try to avoid if-statements that may cause no code to be run, instead use an if-else statement - You always want to print something, otherwise it feels as the program just stops.
Perhaps something like this
public static void main (String[] args)
{
// Scan variables etc
// calculate ratio
double ratio = -1;
if (gender.equalsIgnoreCase("m"))
{
ratio = .73;
}
if (gender.equalsIgnoreCase("f"))
{
ratio = .66;
}
// calculate limit
double limit = -1
if (age > 21)
limit = .08;
limit = .02;
// calculate blood alcohol level
alcAbsorbed = (3.701 * D) / (W * ratio);
alcMetabolized = .015 * H;
double bloodAlcoholLevel = alcAbsorbed - alcMetabolized;
if(bloodAlcoholLevel >= limit)
{
System.out.println("You're over the limit!");
System.out.println("Your BAC is " + BAC + "!");
}
else
{
System.out.println("You're good...for now.");
System.out.println("Your BAC is " + BAC + ".");
}
}
This way your code can be much shorter and easier to read, not to mention change. :-)

Related

how to add try and catch for this Java Program?

and i just created a program for fare with discount. but I dont know where to put the try and catch.
this is the program without try and catch
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String passengerType;
double distance;
double minimumFare = 20;
double fare1, finalFare;
System.out.println("Enter the type of Passenger (Ordinary/Student/Senior): ");
passengerType = input.nextLine();
System.out.println("Enter the Distance: ");
distance = input.nextDouble();
// Condition for "Ordinary Passenger"
if (passengerType.equalsIgnoreCase("Ordinary"))
{
if (distance <= 10)
{
System.out.println("Your Fare is: "+minimumFare);
}
else if (distance > 10)
{
fare1 = (distance - 10) * 2.50;
finalFare = fare1 + minimumFare;
System.out.println("Your Fare is: "+finalFare);
}
}
// Condition for "Student Passenger"
else if (passengerType.equalsIgnoreCase("Student"))
{
if (distance <= 10)
{
finalFare = 20 - (20 * 0.20);
System.out.println("Your Fare is: "+ finalFare);
}
else if (distance > 10)
{
fare1 = ((distance - 10) * 2.50);
finalFare = fare1 + 20 - ((fare1 + 20) * 0.20);
System.out.println("Your Fare is: "+finalFare);
}
}
// Condition for "Senior Passenger"
else if (passengerType.equalsIgnoreCase("Senior"))
{
if (distance <= 10)
{
finalFare = 20 - (20 * 0.30);
System.out.println("Your Fare is: "+ finalFare);
}
else if (distance > 10)
{
fare1 = ((distance - 10) * 2.50);
finalFare = fare1 + 20 - ((fare1 + 20) * 0.30);
System.out.println("Your Fare is: "+ finalFare);
}
}
}
}
the output of the program must be these.(when error input)
thank you so much in advance, its my first time in java language. please don't vote negative ^_^
I'm also new at this, but if you were to run the programme, and try to put in a different input than suggested. For example putting string where you need an int or putting an int where you need string, when you run the programme the compiler will show you the exceptions which you need to catch.
I've altered the start of the programme, just to show you how i'd do it, i'm also not the best but hopefully this puts you on the right track
Scanner input = new Scanner(System.in);
String passengerType = null;
double distance = 0;
double minimumFare = 20;
double fare1, finalFare;
try {
System.out.println("Enter the type of Passenger (Ordinary/Student/Senior): ");
passengerType = input.nextLine();
System.out.println("Enter the Distance: ");
distance = input.nextDouble();
} catch (InputMismatchException e){
System.out.println("Please enter strings for passenger and numbers for distance " + e);
}
also check out the link
When should an IllegalArgumentException be thrown?
Your code never throws any Exception. try and catch blocks are used to catch Exceptions that may be thrown when calling methods that throw them (you can see it on method declaration). If you want to output that an argument is invalid, add an else statement after your conditions, and throw an IllegalArgumentException:
else {
throw new IllegalArgumentException("You did something wrong");
}
Or if you want a "cleaner" error, output it to System.err, so that the user doesn't need to see the stack trace:
else {
System.err.println("Invalid Passenger Type");
}
The same goes to checking if distance is a String, like the other answer showed.
In this case, you are making use of a Scanner which needs to be closed after use, so it is best to go with a try-with-resources statement which will take care of automatically closing the Scanner when it is done.
Also, in order to ensure valid input is gotten, I have included an input checker to keep reading until a valid string is entered for Passenger and a Distance >= 0 is entered.
In the case of Distance, using the input.nextDouble() ensures the input is a valid number and will throw an InputMismatchException if it is not a valid number. Consider reading the input as a String and parse it to Double, that way you have more control over what happens and can demand a new input without the program being terminated. The way it is currently, the program will get terminated as there is no way to read a new input after displaying the error message.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
String passengerType;
double distance;
double minimumFare = 20;
double fare1, finalFare;
try(Scanner input = new Scanner(System.in);){
System.out.println("Enter the type of Passenger (Ordinary/Student/Senior): ");
passengerType = input.nextLine();
while(passengerType == null || passengerType.trim().equals("") || (!passengerType.equals("Ordinary") && !passengerType.equals("Student") && !passengerType.equals("Senior"))){
System.out.println("Valid Passengers are Ordinary/Student/Senior: ");
passengerType = input.nextLine();
}
System.out.println("Enter the Distance: ");
distance = input.nextDouble();
while(distance < 0){
System.out.println("Distance must be greater than or equal to 0: ");
distance = input.nextDouble();
}
System.out.println("Input read: " + passengerType + ", " + distance);
} catch (InputMismatchException e){
System.out.println("Distance must be a number");
return;
} catch (Exception e){
e.printStackTrace();
return;
}
// Condition for "Ordinary Passenger"
if (passengerType.equalsIgnoreCase("Ordinary"))
{
if (distance <= 10)
{
System.out.println("Your Fare is: "+minimumFare);
}
else if (distance > 10)
{
fare1 = (distance - 10) * 2.50;
finalFare = fare1 + minimumFare;
System.out.println("Your Fare is: "+finalFare);
}
}
// Condition for "Student Passenger"
else if (passengerType.equalsIgnoreCase("Student"))
{
if (distance <= 10)
{
finalFare = 20 - (20 * 0.20);
System.out.println("Your Fare is: "+ finalFare);
}
else if (distance > 10)
{
fare1 = ((distance - 10) * 2.50);
finalFare = fare1 + 20 - ((fare1 + 20) * 0.20);
System.out.println("Your Fare is: "+finalFare);
}
}
// Condition for "Senior Passenger"
else if (passengerType.equalsIgnoreCase("Senior"))
{
if (distance <= 10)
{
finalFare = 20 - (20 * 0.30);
System.out.println("Your Fare is: "+ finalFare);
}
else if (distance > 10)
{
fare1 = ((distance - 10) * 2.50);
finalFare = fare1 + 20 - ((fare1 + 20) * 0.30);
System.out.println("Your Fare is: "+ finalFare);
}
}
}
}

Trying to keep new ending balance if while loop repeats

I have to create a game that prompts the user to put in a starting balance and then place a bet. Then they win or lose and their balance is added or subtracted accordingly. My problem is that I don't know how to make the program remember the final balance before starting over in the while loop if the player wants to play again. My balance stays as the original first balance entered when the user is prompted. I'm sorry if this is a repeat, but I couldn't find a question like this and I've been searching for over an hour. Thanks in advance.
import static java.lang.Math.*;
import java.util.Scanner;
public class BetGame
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int die1, die2;
boolean looping = true;
System.out.println("Please enter your starting balance in whole dollars:");
double balance = in.nextDouble();
System.out.println("Your beginning balance is " + balance + ", good luck!!");
int guess = 0;
double bet2 = 0;
double endingBalance = 0;
while(looping) {
while (guess < 3) {//to allow the user to do this only 3 times
System.out.println("Enter a valid bet:");
double bet = in.nextDouble();
if (bet >= balance || bet >= endingBalance){
System.out.println("That is more than your balance.");
}
else if (bet < balance || bet < endingBalance) {
bet2 = 0 + bet;
break;
}
guess++;
if (guess == 3) {
looping = false;
System.out.println("You have entered three invalid bets in a row. Please leave the casino.");
}
}
die1 = RollDie();
die2 = RollDie();
int sum = die1 + die2;
if (2 <= sum && sum <= 6) {
System.out.println("The roll is " + die1 + " and " + die2 + " for a " + sum + " for a win!");
endingBalance = balance + bet2;
}
else if (7 <= sum && sum <= 12) {
System.out.println("The roll is " + die1 + " and " + die2 + " for a " + sum + " for a lose!");
endingBalance = balance - bet2;
}
System.out.println("Your balance is " + endingBalance);
System.out.println("Do you want to roll again?");
String answer = in.next();
if ((answer.equals("n")) || (answer.equals("N"))) {
looping = false;
}
}
System.out.println("Your balance is " + endingBalance + ". Better luck next time! Have a wonderful evening!");
}
static int RollDie()
{
int min = 1;
int max = 6;
return myRandomInteger(min, max);
}
static int myRandomInteger(int min, int max)
{
double range = max - min + 1.0;
int randomNum = (int)(range * Math.random()) + min;
return randomNum;
}
}
You can store the balance in a variable
double balance = in.nextDouble();
double originalBalance = balance;

How Can I Get Exception in my try catch in Java?

So I'm making a program and I want an exception, so the program wont crash.
If the user puts a string that is not in the else if statements then it would not crash.
Also, I tried doing that for the integer, so if someone tries to write something that is not an integer it wont crash. And the program will catch it and would say that it isn't an integer.
How can I get exception in my try catch in java.
Thank for your help
Here is the code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class WeightOnADifferentPlanet {
public static void main ( String[] args ){
Scanner scan = new Scanner ( System.in );
System.out.println("Where do you want to travel:?");
try{
String planetName = scan.nextLine();
}
catch(/*need help here*/){
System.out.println("Please check your spelling");
}
System.out.println("Please enter your weight:");
try{
int weight = scan.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("That is not an integer");
}
double earthCalculation = weight * 1.0;
double jupiterCalculation = weight * (21.0 / 8.0); //check
double marsCalculation = weight * (3.0 / 8.0);
double mercuryCalculation = weight * (3.0 / 10.0);
double neptuneCalculation = weight * (11.0 / 10.0); //check
double plutoCalculation = weight * (7.0 / 10.0);
double saturnCalculation = weight * (6.0 / 5.0); //check
double uranusCalculation = weight * (9.0 / 10.0);
double venusCalculation = weight * (7.0 / 8.0);
if (planetName.equalsIgnoreCase("Earth"))
{
System.out.println("Your weight on "+planetName+" is: "+earthCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Jupiter"))
{
System.out.println("Your weight on "+planetName+" is: "+jupiterCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Mars"))
{
System.out.println("Your weight on "+planetName+" is: "+marsCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Mercury"))
{
System.out.println("Your weight on "+planetName+" is: "+mercuryCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Neptune"))
{
System.out.println("Your weight on "+planetName+" is: "+neptuneCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Pluto"))
{
System.out.println("Your weight on "+planetName+" is: "+plutoCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Saturn"))
{
System.out.println("Your weight on "+planetName+" is: "+saturnCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Uranus"))
{
System.out.println("Your weight on "+planetName+" is: "+uranusCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Venus"))
{
System.out.println("Your weight on "+planetName+" is: "+venusCalculation+" pounds.");
}
}
}
}
I believe scan.nextInt(); will only scan an integer anyways, so there shouldn't be any need to catch non integers
There are several things wrong with your program:
String planetName needs to be declared outside of the try block.
You shouldn't have planetName = scan.nextLine(); in a try/catch. You should figure out a way to keep asking the user for a planet name until they get a proper one.
Also, the int weight needs to be declared outside of the try block.
Same thing here, you need to figure out a way to keep asking the user for an integer if they don't give you one (e.g. you get an exception).
EDIT: As suggested by MasterBlaster, you should also close out your scanner with scan.close()
You don't really need to use exceptions. You can enter anything for planet and it won't crash, since you are checking for nextLine(). For weight, just check if scan.hasNextInt() before setting the weight.
import java.util.Scanner;
public class WeightOnADifferentPlanet {
public static void main ( String[] args ) {
Scanner scan = new Scanner(System.in);
System.out.print("Where do you want to travel? ");
String planetName = scan.nextLine();
System.out.print("Please enter your weight: ");
int weight = 0;
if (scan.hasNextInt()) {
weight = scan.nextInt();
double earthCalculation = weight * 1.0;
double jupiterCalculation = weight * (21.0 / 8.0); //check
double marsCalculation = weight * (3.0 / 8.0);
double mercuryCalculation = weight * (3.0 / 10.0);
double neptuneCalculation = weight * (11.0 / 10.0); //check
double plutoCalculation = weight * (7.0 / 10.0);
double saturnCalculation = weight * (6.0 / 5.0); //check
double uranusCalculation = weight * (9.0 / 10.0);
double venusCalculation = weight * (7.0 / 8.0);
if (planetName.equalsIgnoreCase("Earth")) {
System.out.println("Your weight on " + planetName + " is: " + earthCalculation + " pounds.");
} else if (planetName.equalsIgnoreCase("Jupiter")) {
System.out.println("Your weight on " + planetName + " is: " + jupiterCalculation + " pounds.");
} else if (planetName.equalsIgnoreCase("Mars")) {
System.out.println("Your weight on " + planetName + " is: " + marsCalculation + " pounds.");
} else if (planetName.equalsIgnoreCase("Mercury")) {
System.out.println("Your weight on " + planetName + " is: " + mercuryCalculation + " pounds.");
} else if (planetName.equalsIgnoreCase("Neptune")) {
System.out.println("Your weight on " + planetName + " is: " + neptuneCalculation + " pounds.");
} else if (planetName.equalsIgnoreCase("Pluto")) {
System.out.println("Your weight on " + planetName + " is: " + plutoCalculation + " pounds.");
} else if (planetName.equalsIgnoreCase("Saturn")) {
System.out.println("Your weight on " + planetName + " is: " + saturnCalculation + " pounds.");
} else if (planetName.equalsIgnoreCase("Uranus")) {
System.out.println("Your weight on " + planetName + " is: " + uranusCalculation + " pounds.");
} else if (planetName.equalsIgnoreCase("Venus")) {
System.out.println("Your weight on " + planetName + " is: " + venusCalculation + " pounds.");
} else {
System.out.println("Planet not recognized");
}
} else {
System.out.println("Invalid weight");
}
scan.close();
}
}
So I ended up fixing it and here is the result.
import java.util.InputMismatchException;
import java.util.Scanner;
public class WeightOnADifferentPlanet {
static Scanner scan = new Scanner ( System.in );
public static void main ( String[] args ){
System.out.println("What planet do you want to travela:?");
String planetName = scan.nextLine();
System.out.println("Please enter your weight:");
int weight = Integer();
//int weight = scan.nextInt();
double earthCalculation = weight * 1.0;
double jupiterCalculation = weight * (21.0 / 8.0); //check
double marsCalculation = weight * (3.0 / 8.0);
double mercuryCalculation = weight * (3.0 / 10.0);
double neptuneCalculation = weight * (11.0 / 10.0); //check
double plutoCalculation = weight * (7.0 / 10.0);
double saturnCalculation = weight * (6.0 / 5.0); //check
double uranusCalculation = weight * (9.0 / 10.0);
double venusCalculation = weight * (7.0 / 8.0);
if (planetName.equalsIgnoreCase("Earth"))
{
System.out.println("Your weight on "+planetName+" is: "+earthCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Jupiter"))
{
System.out.println("Your weight on "+planetName+" is: "+jupiterCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Mars"))
{
System.out.println("Your weight on "+planetName+" is: "+marsCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Mercury"))
{
System.out.println("Your weight on "+planetName+" is: "+mercuryCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Neptune"))
{
System.out.println("Your weight on "+planetName+" is: "+neptuneCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Pluto"))
{
System.out.println("Your weight on "+planetName+" is: "+plutoCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Saturn"))
{
System.out.println("Your weight on "+planetName+" is: "+saturnCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Uranus"))
{
System.out.println("Your weight on "+planetName+" is: "+uranusCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Venus"))
{
System.out.println("Your weight on "+planetName+" is: "+venusCalculation+" pounds.");
}
else {
System.out.println("Planet not recognized");
}
}
public static int Integer(){
while (true)
{
try
{
return scan.nextInt();
}
catch (InputMismatchException e)
{
scan.next();
System.out.print("That’s not an integer. Try again: ");
}
}
}
}

Java JoptionPane trying to get it to work for sepreate method with double x4

i am trying to get my program to just show the grade and letter grade i know its a mess but i just need it to print but the Netbean says that JOptionPane requires double, double, double, double
package garrett_sprunger_a5;
import java.text.DecimalFormat;
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
*
* #author Garrett
*/
public class Garrett_sprunger_A5 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String inputString; // For reader's input
double TestScore1, //Define TestScore 1
TestScore2, //Define TestScore 2
TestScore3, //Define TestScore 3
AverageScore; //Define AverageScore
Scanner keyboard = new Scanner(System.in); //To hold the users grade
// (somehow i am able to use
// keyboard but can't get the
// varible to match correctly)
DecimalFormat formatter =
new DecimalFormat("#,##0.0"); //format the scores
Scanner Keyboard = new Scanner(System.in);
inputString=
JOptionPane.showInputDialog("\t\nPlease enter Test Score 1");
TestScore1 = Double.parseDouble(inputString);
// input TestScore2
inputString=
JOptionPane.showInputDialog("\t\nPlease enter Test Score 2");
// Convert the input to a double
TestScore2 = Double.parseDouble(inputString);
//input TestScore3
inputString=
JOptionPane.showInputDialog("\t\nPlease enter Test Score 3");
// Convert the input to a double
TestScore3 = Double.parseDouble(inputString);
//Calculate the average score for the tests
AverageScore = Calcaverage(TestScore1, TestScore2, TestScore3);
//AverageScore = (AverageScore +0.5);// applying midpoint roudning
// rule not needed with formated
// rounding
//Display Average test Score
{
if(TestScore1 <0 && TestScore1 >100)
JOptionPane.showMessageDialog(null, "Please enter a Correct" +
" data range between 0 and 100");
}
JOptionPane.showMessageDialog(null, "\t\nYour Test Score 1 is : "
+ formatter.format(TestScore1)
+"\t Grade: "
+ getLetterGrade(TestScore1)
+ "\t\nYour Test Score 2 is : "
+ formatter.format(TestScore2)
+ "\t Grade: "
+ getLetterGrade(TestScore2)
+ "\t\nYour Test Score 3 is : "
+ formatter.format(TestScore3)
+ "\t Grade: "
+ getLetterGrade(TestScore3)
+ "\t\nYour Average Score is : "
+ formatter.format(AverageScore)
+ "\t Grade: "
+ getLetterGrade(AverageScore));
}//End main method
public static double Calcaverage(double TestScore1,
double TestScore2, double TestScore3 ) {
double AverageScore = ((TestScore1 + TestScore2 + TestScore3)/3);
return AverageScore;
}
// Determine the letter grade
public static char getLetterGrade(double TestScore1,
double TestScore2,double TestScore3, double AverageScore) {
if (AverageScore >=90) {
return 'A';
} else if (AverageScore >= 70 && AverageScore < 90) {
if (TestScore3 > 90)
return 'A';
} else
return 'B';
if(AverageScore >=50 && AverageScore <70) {
if(((TestScore2 + TestScore3)/2.0) > 70)
return 'C';
} else
return 'D';
if (AverageScore < 50)
return 'f';
else
return '0';
}
public static void displaygrade( double AverageScore,
double TestScore1, double TestScore2,
double TestScore3, char getLetterGrade) {
DecimalFormat formatter = new DecimalFormat("#,##0.0");
JOptionPane.showMessageDialog(null, "\t\nYour Test Score 1 is : " +
formatter.format(TestScore1) +
"\t Grade: " + getLetterGrade(
TestScore1) +
"\t\nYour Test Score 2 is : " +
formatter.format(TestScore2) +
"\t Grade: " + getLetterGrade(
TestScore2) +
"\t\nYour Test Score 3 is : " +
formatter.format(TestScore3) +
"\t Grade: " + getLetterGrade(
TestScore3) +
"\t\nYour Average Score is : " + formatter.format(AverageScore)+
"\t Grade: " + getLetterGrade(
AverageScore));
}
}
I suggest you change the getLetterGrade() method to something which resembles this:
public static char getLetterGrade(double testScore) {
if (testScore >= 90) {
return 'A';
}
else if (testScore >= 80) {
return 'B';
}
//continue using if statements to determine the letter grade
}
Note that the method above only has one parameter, double testScore, which should be more helpful than inputing four doubles at once.
Would also like to point out that this if statement in your code will never run. Should be easy to figure out why:
if(TestScore1 <0 && TestScore1 >100)
JOptionPane.showMessageDialog(null, "Please enter a Correct data range between 0 and 100");

unable to get the correct output for input .11

I have an assignment at school and I have to display the correct change for an amount that is being input by the user that is less than 1.00 but greater than 0. Every amount works except anything in a double digit that has a 1 or a 6 on the tenth spot. for example .11, .16, .21, .26 etc.
this is my code
import java.util.Scanner;
public class AmountChange
{
public static void main(String[] args)
{
//
double amt;
int cents, quarter, dime, nickle, penny;
Scanner keyboard = new Scanner(System.in);
//To get the users input
System.out.println("Change in Coins");
System.out.println("---------------");
System.out.println("Enter the amount less than $1.00, " +
"\nbut more than zero.");
System.out.print("\nEnter amount: ");
amt = keyboard.nextDouble();
//Loop for incorrect input
while ( amt < 0 || amt > 1.00 )
{
System.out.println("Please enter the amount less than $1.00,"
+ "\nbut more than zero.");
System.out.print("\nRe-enter amount: ");
amt = keyboard.nextDouble();
}
//
cents = (int)( amt * 100 + .1 );
quarter = cents/25;
cents %= 25;
dime = cents/10;
cents %= 10;
nickle = cents/5;
cents %= 5;
penny = cents;
// ----------------------------------------------------------
if (quarter > 1)
{
System.out.print("\nYou will need " + quarter + " quarters, ");
}
else if (quarter == 1)
{
System.out.print("\nYou will need " + quarter + " quarter ,");
}
else
{
System.out.print("\nYou will need no quarters, ");
}
// ----------------------------------------------------------
if (dime > 1)
{
System.out.print(dime + " dimes, ");
}
else if (dime == 1)
{
System.out.print(dime + " dime, ");
}
else
{
System.out.print("no dimes, ");
}
// ----------------------------------------------------------
if (nickle > 1)
{
System.out.print(nickle + " nickles, ");
}
else if (nickle == 1)
{
System.out.print(nickle + " nickle, ");
}
else
{
System.out.print("no nickles, ");
}
// ----------------------------------------------------------
if (penny > 1)
{
System.out.print("and " + penny + " pennies.");
}
else if (quarter == 1)
{
System.out.print("and " + penny + " penny.");
}
else
{
System.out.print("and no pennies.");
}
}
}
Ah, the joys of cut and paste :-)
if (penny > 1)
{
System.out.print("and " + penny + " pennies.");
}
else if (quarter == 1) // <<<<< LOOK HERE !!!
{
System.out.print("and " + penny + " penny.");
}
else
{
System.out.print("and no pennies.");
}
That should be penny, not quarter.
And, in fact, it actually does work for .26 (despite your assertion) since quarter is set to 1, the same as penny. In fact it'll work for any value where the number of quarters equals the number of pennies (.26, .52, .78), but only by accident.
As an aside, one other thing you may want to think about is refactoring all that repeated code with something like:
import java.util.Scanner;
public class Test
{
static double getAmount(Scanner keyboard) {
System.out.println("Enter the amount between zero and $1.00.");
System.out.print("\nEnter amount: ");
return keyboard.nextDouble();
}
static String mkeTxt (int val, String prefix, String singular, String plural) {
if (val == 0)
return prefix + "no " + plural;
if (val == 1)
return prefix + "1 " + singular;
return prefix + val + " " + plural;
}
public static void main(String[] args)
{
double amt;
int cents, quarter, dime, nickle, penny;
Scanner keyboard = new Scanner(System.in);
System.out.println("Change in Coins");
System.out.println("---------------");
amt = getAmount(keyboard);
while ( amt < 0 || amt > 1.00 )
amt = getAmount(keyboard);
cents = (int)( amt * 100 + .1 );
quarter = cents/25;
cents %= 25;
dime = cents/10;
cents %= 10;
nickle = cents/5;
cents %= 5;
penny = cents;
System.out.print("\nYou will need ");
System.out.print(mkeTxt(quarter,"", "quarter", "quarters"));
System.out.print(mkeTxt(dime,", ", "dime", "dimes"));
System.out.print(mkeTxt(nickle,", ", "nickle", "nickles"));
System.out.print(mkeTxt(penny," and ", "penny", "pennies"));
System.out.println(".");
}
}
The use of a function to output the prompt and accept input makes the user input code a little easier to maintain as you only need to change interaction in one place.
The real saver is the mkTxt() function to give you a string that auto-magically adjusts to the quantity of coins. It gets rid of that voluminous group of if/then/else blocks in main(), aiding readability somewhat.
If you ever find yourself doing a similar thing many times but with different values, that positively cries out to be changed into a function or loop of some description.
You just have a simple typo!
Change:
else if (quarter == 1){
System.out.print("and " + penny + " penny.");
} else {
System.out.print("and no pennies.");
}
To,
else if (penny == 1){
System.out.print("and " + penny + " penny.");
} else {
System.out.print("and no pennies.");
}

Categories

Resources