How Can I Get Exception in my try catch in Java? - 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: ");
}
}
}
}

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);
}
}
}
}

BMI calcuator, several methods, code check

It's my first program with several methods
1st has to convert height to inches
2nd calculate BMI
3rd receive BMI and and return the status
4th which is the main, has to call for input and generate output
The problem is that it doesnt calculate the BMI - it outputs 0.
When I run it in just one method, it works fine. What might be wrong?
package bmiCalculator;
java.util.Scanner;
public class BmiCalculator {
public static double bmi;
public static int height;
public static int feet;
public static int inches;
public static int weight;
public static String status;
public static void convertToInches (){
height = feet * 12 + inches;
}
public static void bmiCalculator (){
bmi = (weight * 703) / (height * height);
}
public static void weightStatus () {
if (bmi < 18.5){
status = "underweight";
}
else if (bmi <= 24.9){
status = "normal";
}
else if (bmi <= 29.9){
status = "overweight";
}
else if (bmi >= 30){
status = "obese";
}
}
public static void main (String[] args){
System.out.println("Put your height in ft and inches");
Scanner sc = new Scanner(System.in);
feet = sc.nextInt();
inches = sc.nextInt();
System.out.println("Put your weight in pounds");
weight = sc.nextInt();
System.out.println("Height: " + feet + " feet, " + inches + " inches");
System.out.println("Weight: " + weight + " pounds");
System.out.println("Your BMI is " + bmi + "category" + status);
}
}
Declaring those method does not mean all will execute. you need to call those methods from main accordingly.
for example:
...
System.out.println("Put your weight in pounds");
weight = sc.nextInt();
System.out.println("Height: " + feet + " feet, " + inches + " inches");
System.out.println("Weight: " + weight + " pounds");
// call corresponding method to calculate:
convertToInches();
bmiCalculator();
weightStatus();
// now all of those method are executed.
System.out.println("Your BMI is " + bmi + "category" + status);
Declaring all those methods and properties as static is not a good practice. Please learn how OOP works.
first, you need to call the methods after the user enter values like this..
...
System.out.println("Put your weight in pounds");
weight = sc.nextInt();
convertToInches();
bmiCalculator();
weightStatus();
System.out.println("Height: " + feet + " feet, " + inches + " inches");
...
The order of calling the methods is important because there are dependences between them.
Also, you need to convert the divisor and dividend to double before the BMI division because int/int = int and java round the value.
public static void bmiCalculator() {
bmi = (double)(weight * 703) / (double)(height * height);
}

Calculating employee pay with methods

I am having trouble with a part of an assignment where i have a method to calculate the regular pay of an employee but if the hours worked is over 40 then the rest is overtime but in if the user types in 50 hours with a 10 dollar rate it will print out 500 but i want it to to only print out 40 of those 50 hours and take the rest as overtime.
package paytime;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String firstName, lastName, choice;
double hoursWorked, hourlyWage, weeklyPay;
Employee one = new Employee();
System.out.print("Enter Y to process employee or any other key to end: ");
choice = scn.nextLine();
if (choice.equalsIgnoreCase("Y"))
{
System.out.print("Enter employee number: ");
int number = scn.nextInt();
while (!one.findEmpNumber(number))
{
System.out.print("Invlaid, enter a proper employee number: ");
number = scn.nextInt();
}
System.out.print("Enter first name: ");
firstName = scn.next();
System.out.print("Enter last name: ");
lastName = scn.next();
System.out.print("Enter hours worked: ");
hoursWorked = scn.nextDouble();
while (hoursWorked < 0)
{
System.out.print("Negative hours not allowed. Enter hours worked: ");
hoursWorked = scn.nextDouble();
}
System.out.print("Enter hourly wage: $");
hourlyWage = scn.nextDouble();
while (hourlyWage < 0 || hourlyWage > 100)
{
System.out.print("Negative wage is not allowed or wage entered is to high. Enter hourley wage: $");
hourlyWage = scn.nextDouble();
}
System.out.println(" ");
if (hoursWorked <= 40.0)
{
System.out.println("Worker " + number + " Paycheck Information: ");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callWeeklyPay(hoursWorked = 40, hourlyWage));
System.out.println("Income Taxes is: " + one.callIncomeTax());
System.out.println("Net Pay is: " + one.callNetPay());
}
else if (hoursWorked > 40.0)
{
System.out.println("Worker " + number + " Paycheck Information: ");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callWeeklyPay(hoursWorked, hourlyWage));
System.out.println("Income Taxes is: " + one.callIncomeTax());
System.out.println("Net Pay is: " + one.callNetPay());
System.out.println(" ");
System.out.println(" ");
System.out.println("Worker " + number + " Overtime Calculation");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callOvertimePay());
}
}
else
{
System.out.println("Total number of Employees processed: ");
}
}
}
package paytime;
public class Employee {
private int empNumbers [] = {101, 103, 106, 109, 110, 113, 116, 118, 120};
public double weeklyPay, hoursWorked, hourlyWage, incomeTax, netPay, actualOvertimeHours, overtimePay, overtimeHours;
public double overtimeWage = hourlyWage * 1.5;
public boolean findEmpNumber(int number)
{
boolean found = false;
for (int sub = 0; sub < empNumbers.length; sub++)
{
if (number == empNumbers[sub])
{
found = true;
break;
}
}
return found;
}
private void calculateWeeklyPay(double hoursWorked, double hourlyWage) {
weeklyPay = hoursWorked * hourlyWage;
}
public double callWeeklyPay(double hoursWorked, double hourlyWage) {
calculateWeeklyPay(hoursWorked, hourlyWage);
return weeklyPay;
}
private void calculateIncomeTax() {
if (weeklyPay > 0.0 && weeklyPay <= 300.0)
{
incomeTax = weeklyPay * 0.10;
}
else if (weeklyPay > 300.1 && weeklyPay <= 400.0)
{
incomeTax = weeklyPay * 0.12;
}
else if (weeklyPay > 400.1 && weeklyPay <= 500.0)
{
incomeTax = weeklyPay * 0.15;
}
else if (weeklyPay > 500.1)
{
incomeTax = weeklyPay * 0.20;
}
}
public double callIncomeTax() {
calculateIncomeTax();
return incomeTax;
}
private void calculateNetPay() {
netPay = weeklyPay - incomeTax;
}
public double callNetPay() {
calculateNetPay();
return netPay;
}
private void calculateOvertimePay() {
overtimeHours = hoursWorked -40;
overtimePay = ovetimeHours * overtimeWage;
}
public double callOvertimePay() {
calculateOvertimePay();
return overtimePay;
}
}
When you call callWeeklyPay method subtract 40 from the hoursWorked.
one.callWeeklyPay(hoursWorked - 40, hourlyWage));
But I would suggest moving the logic of checking for overtimes(hours exceeding 40) inside the Employee class (callWeeklyPay method) itself.

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");

if statement logic not working

so i have these two classes called shipment and insurance, one calculates the price for shipping and the other adds the insurance. The shipment logic is working just fine but for some reason the if statements in Insurance class is not working i dont know whats going on. The output for the Insurance cost is always 2.45. why does it do this?
Shipment class:
package theshipment;
public class Shipment extends Main {
protected double weight = Double.parseDouble(savedArgs[1]);
protected double shippingCost;
protected double methodCost;
protected String method = savedArgs[2];
public void calculateShippingCost(){
if (weight<=10||weight>=1){
if (method.equalsIgnoreCase("T"))
methodCost = weight * 3.00;
else if (method.equalsIgnoreCase("A"))
methodCost = weight * 4.00;
else if (method.equalsIgnoreCase("M"))
methodCost = weight * 2.00;
else{}
}else if (weight<=20||weight>=10.1){
if (method.equalsIgnoreCase("T"))
methodCost = weight * 2.45;
else if (method.equalsIgnoreCase("A"))
methodCost = weight * 3.00;
else if (method.equalsIgnoreCase("M"))
methodCost = weight * 1.75;
else{}
}else if (weight>20){
if (method.equalsIgnoreCase("T"))
methodCost = weight * 1.95;
else if (method.equalsIgnoreCase("A"))
methodCost = weight * 2.50;
else if (method.equalsIgnoreCase("M"))
methodCost = weight * 1.55;
else{}
}else{}
}
}
And the insurance class:
package theshipment;
public class Insurance extends Shipment{
private void calculateInsurance(){
if (methodCost<=10.0||methodCost>=0.0)
shippingCost = methodCost + 2.45;
else if(methodCost<=30.0||methodCost>=10.1)
shippingCost = methodCost + 3.95;
else if(methodCost>=30.01)
shippingCost = methodCost + 5.55;
else{}
}
public void run(){
calculateShippingCost();
calculateInsurance();
}
public String displayOrder(){
return ("Method cost: " + methodCost + " " + "Insurance cost: " +
(shippingCost-methodCost) + " Total shipping cost: " + shippingCost);
}
}
methodCost<=10.0||methodCost>=0.0 that means it will be true when methodCost will be bigger than 0 OR smaller than 10,
I believe you want range not all numbers change it to methodCost<=10.0 && methodCost>=0.0

Categories

Resources