I am trying to do a simple calculation. I can't figure out how to subtract "double admissionPrice" in the last if-else statements.
Its pointing to the subtraction sign giving me this error message:
operator - cannot be applied to java.lang.String,double
Please help. thanks.
import java.text.*;
import java.util.Scanner;
class IMC {
public static void main(String[] args) {
int numEmployees = 0;
double costPerAttendee = 0.00;
int employeeDiscount;
double admissionPrice = 0.00;
Scanner keyboard = new Scanner (System.in);
System.out.print("Enter amount of employees attending: ");
numEmployees = keyboard.nextInt();
System.out.print("Have any employees attended previously? \n For: YES=1 or NO=2"
);
employeeDiscount = keyboard.nextInt();
if (numEmployees == 1) { admissionPrice = 695.00;
} else if (numEmployees == 2 || numEmployees == 3 ||numEmployees == 4) { admissionPrice = 545.00;
} else if (numEmployees >= 5 ||numEmployees >= 6 ||numEmployees >= 7 ||numEmployees >= 8){ admissionPrice = 480.00;
} else if (numEmployees >= 9) { admissionPrice = 395.00;
}
System.out.print("The cost per attendee is: " + admissionPrice );
if (employeeDiscount == 1){
System.out.print("Total price after discount (15%) is : " + admissionPrice - (admissionPrice * 0.15) );
} else if (employeeDiscount == 2) {
System.out.print("No discount. Total price is still: " + admissionPrice);
}
}
}
Place parenthesis around (admissionPrice - (admissionPrice * 0.15) ). Right now, it concatenates admissionPrice on to "Total price after discount (15%) is : " before attempting subtraction.
The + operator in your println() statement is taking precedence and converting admissionPrice to a String.
Put your arithmetic operation in parenthesis.
System.out.print("Total price after discount (15%) is : " + (admissionPrice - (admissionPrice * 0.15)));
^ ^
You need to add () to fix the precedence, else, as the error indicates, you are subtracting, not from admissionPrice but the string that is formed of "To....:" + admissionPrice
Related
I am a new coder. Working on an assignment. This is also my first post here so I apologize if it's a little sloppy.
I'm having some troubles with my if/else statements in Java...the "if" conditions seem to work okay. But my "else" conditions do not. Take a look at the code and the build results below.
Basically, I enter an ingredient. And then I put in the number of cups needed. And the number of calories the ingredient has per x cup. That all seems to work as long as I input what I want to for "successful" results.
Successful Build Image
But when I start to input values outside of my criteria, my application doesn't seem to care. If I input 0, I should get that output of "your response is invalid" or whatever it is I coded. But it just seems to skip over that entirely.
Bad Code Image
package recipe_collection_manager;
import java.util.Scanner;
public class Ingredient {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
//Initializes the variables
String nameOfIngredient = "";
int numberCups = 0;
int numberCaloriesPerCup = 0;
int totalCaloriesPerCup = 0;
double totalCalories = 0.0;
// Enter the name of the ingredient.
System.out.println("Please enter the name of the ingredient: ");
nameOfIngredient = scnr.next();
// Enter the number of cups needed for the ingredient.
// If Else statements used to establish if the number of cups is valid.
System.out.println("Please enter the number of cups of "
+ nameOfIngredient + " we'll need. The number of cups must be between 1 and 100: ");
numberCups = scnr.nextInt();
if (numberCups >= 1 || numberCups <= 100) {
System.out.println("The number of cups is valid.");
} else if (numberCups <= 1 || numberCups >= 100) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Enter the number of calories used per cup.
// If Else statements are used to establish if the number of calories is valid.
System.out.println("Please enter the number of calories per cup: ");
numberCaloriesPerCup = scnr.nextInt();
if (numberCaloriesPerCup >= 1 || numberCaloriesPerCup <= 1000) {
System.out.println("The number of calories is valid.");
} else if (numberCaloriesPerCup <= 1 || numberCaloriesPerCup >= 1000) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Calculation for totalCalories based on numberCups and numberCaloriesPerCup
if (numberCups > 0 && numberCaloriesPerCup > 0) {
totalCalories = numberCups * numberCaloriesPerCup;
}
System.out.println(nameOfIngredient + " uses " + numberCups
+ " cups and has " + totalCalories + " calories.");
}
}
Problem was in line:
if (numberCups >= 1 || numberCups <= 100) {
...
}
When you entered 0, program checked if 0 is greater or equal to 1, and that was false but you had also "or" condition ( || ), and in that condition you were checking if 0 <= 100 and because that is true, false || true gives true and that's why your if statement was correct. You needed to use "and" ( && ) instead of "or". There was flaw in your logic.
Test code below, it should work now:
package recipe_collection_manager;
import java.util.Scanner;
public class Ingredient {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
//Initializes the variables
String nameOfIngredient = "";
int numberCups = 0;
int numberCaloriesPerCup = 0;
int totalCaloriesPerCup = 0;
double totalCalories = 0.0;
// Enter the name of the ingredient.
System.out.println("Please enter the name of the ingredient: ");
nameOfIngredient = scnr.next();
// Enter the number of cups needed for the ingredient.
// If Else statements used to establish if the number of cups is valid.
System.out.println("Please enter the number of cups of "
+ nameOfIngredient + " we'll need. The number of cups must be between 1 and 100: ");
numberCups = scnr.nextInt();
if (numberCups >= 1 && numberCups <= 100) {
System.out.println("The number of cups is valid.");
} else if (numberCups <= 1 || numberCups >= 100) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Enter the number of calories used per cup.
// If Else statements are used to establish if the number of calories is valid.
System.out.println("Please enter the number of calories per cup: ");
numberCaloriesPerCup = scnr.nextInt();
if (numberCaloriesPerCup >= 1 || numberCaloriesPerCup <= 1000) {
System.out.println("The number of calories is valid.");
} else if (numberCaloriesPerCup <= 1 || numberCaloriesPerCup >= 1000) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Calculation for totalCalories based on numberCups and numberCaloriesPerCup
if (numberCups > 0 && numberCaloriesPerCup > 0) {
totalCalories = numberCups * numberCaloriesPerCup;
}
System.out.println(nameOfIngredient + " uses " + numberCups
+ " cups and has " + totalCalories + " calories.");
}
}
Just to clarify. The following statement
if(numberCups >= 1 || numberCups <= 100) {
...
}
Is true any number of cups. Any number of cups >= 1 will be caught by the first condition. Any number of cups <= 0 will be caught by the second condition since in that case they will all be less than 100. With a logical || only one condition is required to be true for the statement to be true.
In fact,
if(numberOfCups is >= A || numberOfCups <= B) {
...
}
will always be true as long as B >= A-1.
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);
}
}
}
}
I'm not sure why it isn't working, eclipse keeps telling me "A" "B" and "C" aren't defined as variables and keeps suggesting to make them defined ("A" "B" and "C" are all options the user can input to get a result). Could someone find a fix ?
/*
* George Sayegh
* Febuary 17th 2016
* program for phone plan
*/
import javax.swing.JOptionPane;
public class Feb21716 {
public static void main(String[] args) {
double Package, Data, Bill;
//Get Package
String Packagetext = JOptionPane.showInputDialog("Enter your wireless service carrier plan"
+ "\n Package A: For $29.99 per month 2GB of data is provided. Additional data is $10.00 per GB."
+ "\n Package B: For $39.99 per month 4GB of data is provided. Additional data is $5.00 per GB. "
+ "\n Package C: For $49.99 per month unlimited data is provided."
+ "\n Please enter only the letter in Upper Case ex. Package A = A");
Package = Double.parseDouble(Packagetext);
//Get Amount of Data Used
String Datatext = JOptionPane.showInputDialog("Please enter the Amount of data you use in GB"
+ "\n Please note, just enter the numbers "
+ "\n ex. 750 MB = .75 ");
if(( Package == A )&&(Data <= 2)){
// when Package is A and less than 2GB
Bill = 29.99;
} else if ((Package == A)&&(Data > 2)) {
// when package is A and more than 2GB
Bill = 29.99 + 10 * Data;
} else if ((Package == B)&&(Data <= 4)) {
// when package is B and less than 4GB
Bill = 39.99;
} else if ((Package == B)&&(Data > 4)){
// when package is B and more than 4GB
Bill = 29.99 + 10 * Data;
} else if ((Package == C)&&(Data < 50)){
// when package is C and less than 50gb
Bill = 49.99;
} else if ((Package == C)&&(Data > 50)){
// when package is C and more than 50gb
Bill = JOptionPane.showMessageDialog(null, "You have entered an invalid Number");
}
JOptionPane.showMessageDialog(null, "Your bill is: $" + Bill);
}
}
}
/*
* TMKRAY
* Febuary 18th 2016
* program for phone plan corrected
*/
import java.util.*;
import java.util.Scanner;
import java.text.DecimalFormat;
public class Feb21716 {
private static DecimalFormat df2 = new DecimalFormat(".##");
public static void main(String[] args) {
double total;
System.out.println("Enter your wireless service carrier plan"
+ "\n Package A: For $29.99 per month 2GB of data is provided. Additional data is $10.00 per GB."
+ "\n Package B: For $39.99 per month 4GB of data is provided. Additional data is $5.00 per GB. "
+ "\n Package C: For $49.99 per month unlimited data is provided."
+ "\n Please enter only the letter in Upper Case ex. Package A = A");
Scanner sc = new Scanner(System.in);
String whichPackage = sc.nextLine();
System.out.println("Please enter the Amount of data you use in GB"
+ "\n Please note, just enter the numbers "
+ "\n ex. 750 MB = .75 ");
Scanner dText = new Scanner(System.in);
double packageSize = dText.nextDouble();
if(( whichPackage .equals( "A" ))&&(packageSize <= 2)){
// when Package is A and less than 2GB
total = 29.99;
System.out.println("Your Bill is: " +df2.format(total));
} else if(( whichPackage .equals( "A" ))&&(packageSize > 2)) {
// when package is A and more than 2GB
total = 29.99 + 10 * (packageSize-2);
System.out.println("Your Bill is: " + df2.format(total));
} else if(( whichPackage .equals( "B" ))&&(packageSize <= 4)) {
// when package is B and less than 4GB
total = 39.99;
System.out.println("Your Bill is: " + df2.format(total));
} else if(( whichPackage .equals( "B" ))&&(packageSize > 4)){
// when package is B and more than 4GB
total = 29.99 + 10 * (packageSize-4);
System.out.println("Your Bill is: " + df2.format(total));
} else if(( whichPackage .equals( "C" ))&&(packageSize < 50)){
// when package is C and less than 50gb
total = 49.99;
System.out.println("Your Bill is: " + df2.format(total));
} else if(( whichPackage .equals( "C" ))&&(packageSize > 50)){
// when package is C and more than 50gb
total= 0;
System.out.println("You didnt enter a valid number "+total);
}
}
}
Inside your if statements you are comparing Package which is a double with A,B and C which are undeclared variables .
JOptionPane.showInputDialog("your text here");
returns a String.
A better approach for you is to do something like the following.
String userInput = JOptionPane.showInputDialog("Insert package A,B or C");
and then inside your if statement use the equals method
if(userInput.equals("A")) {
// code to run if "A" is the userInput
}
As a final note, try to follow proper code conventions as it will dramatically improve how readable your code is for yourself and others.
Instead of declaring Package a double, you can make it a char variable and Data and Bill could remain doubles. Because Package represents a single letter value (A,B,C), it would be better to store as a char. Doubles represent numerical values not letters.
So this is how it would look in the code:
public static void main(String[] args) {
double data, bill;
char packageVal;
char package_A, package_B, package_C;
//Get Package
String packagetext = JOptionPane.showInputDialog("Enter your wireless service carrier plan"
+ "\n Package A: For $29.99 per month 2GB of data is provided. Additional data is $10.00 per GB."
+ "\n Package B: For $39.99 per month 4GB of data is provided. Additional data is $5.00 per GB. "
+ "\n Package C: For $49.99 per month unlimited data is provided."
+ "\n Please enter only the letter in Upper Case ex. Package A = A");
packageVal = Packagetext.charAt(0);
//Get Amount of Data Used
String datatext = JOptionPane.showInputDialog("Please enter the Amount of data you use in GB"
+ "\n Please note, just enter the numbers "
+ "\n ex. 750 MB = .75 ");
data = Double.parseDouble(datatext);
if(( packageVal == 'A' )&&(data <= 2)){
// when Package is A and less than 2GB
bill = 29.99;
} else if ((packageVal == 'A')&&(data > 2)) {
// when package is A and more than 2GB
bill = 29.99 + 10 * Data;
} else if ((packageVal == 'B')&&(data <= 4)) {
// when package is B and less than 4GB
bill = 39.99;
} else if ((packageVal == 'B')&&(data > 4)){
// when package is B and more than 4GB
bill = 29.99 + 10 * Data;
} else if ((packageVal == 'C')&&(data < 50)){
// when package is C and less than 50gb
bill = 49.99;
} else if ((packageVal == 'C')&&(data > 50)){
// when package is C and more than 50gb
bill = JOptionPane.showMessageDialog(null, "You have entered an invalid Number");
}
JOptionPane.showMessageDialog(null, "Your bill is: $" + bill);
This should be enough to solve your problem.
I have attempted using a nested if in the following code. I have initialized variables but the compiler is telling me that the variable named 'bill' is not initialized even though it has been. Why is the compiler not recognizing the value assigned to the variable? Please see the notes in the code below.
package killMe;
import java.util.Scanner;
public class Kill_Me {
static Scanner console = new Scanner(System.in);
static double PREMIUM_SERVICE = 55.00;
static double PREMIUM_DAY_OVERTIME_MIN = 0.20;
static double PREMIUM_NIGHT_OVERTIME_MIN = 0.15;
static double REGULAR_SERVICE = 30.00;
static double REGULAR_OVERTIME_MIN = 0.40;
public static void main(String[] args) {
int acctNumber;
double premiumDayMin;
double premiumNightMin;
double bill;
double minutes;
String name;
String premium = "PREMIUM";
String regular = "REGULAR";
System.out.println("What is the Account Number? ");
acctNumber = console.nextInt();
System.out.println("What is the Customer Name? ");
name = console.next();
System.out.println("Is the Service Code Premium or Regular? ");
String strService = console.next();
String strServiceCAP = strService.toUpperCase();
if(strServiceCAP.compareTo(premium) == 0)
{
System.out.println("How many Day Minutes were used? ");
premiumDayMin = console.nextDouble();
System.out.println("How many Night Minutes were used? ");
premiumNightMin = console.nextDouble();
if(premiumDayMin <0 && premiumNightMin <0)
{
System.out.println("Minutes cannot be less than 0 ");
}
else if(premiumDayMin <= 75 && premiumNightMin <= 100)
{
bill = PREMIUM_SERVICE;
}
else bill = PREMIUM_SERVICE + (premiumDayMin - 75) * PREMIUM_DAY_OVERTIME_MIN + (premiumNightMin - 100)
* PREMIUM_NIGHT_OVERTIME_MIN;
minutes = premiumDayMin + premiumNightMin;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Premium Service Used (Day): " + premiumDayMin);
System.out.println("Minutes Premium Service Used (Night): " + premiumNightMin);
System.out.println("Amount Due: " + bill); // I get an error here stating, "The local variable 'bill' may not have been initialized".
}
else if(strServiceCAP.compareTo(regular) == 0)
{
System.out.println("How many minutes were used? ");
minutes = console.nextDouble();
bill = REGULAR_SERVICE + (minutes - 50) * REGULAR_OVERTIME_MIN;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Regular Service Used: " + minutes);
System.out.println("Amount Due: " + bill); // I DO NOT receive an error message here.
}
else
{
System.out.println("Invalid Service Type");
}
} // End of main
} // End of class
No, bill has not been initialized in all cases.
Understand this: the Java compiler will never, ever, evaluate boolean expressions; Simplified version:
double bill;
if (c1) {
bill = v1;
} else if (c2) {
bill = v2;
}
// try and use bill here
Even if, according to your logic, boolean expressions c1 and c2 may cover all possible cases, the compiler cannot ensure that this is the case.
This is the root cause of your error, however deep your if/else, switch, etc statements may be nested.
They were some problems with else statement and variable declarations.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
double PREMIUM_SERVICE = 25.00;
double PREMIUM_DAY_OVERTIME_MIN = 0.10;
double PREMIUM_NIGHT_OVERTIME_MIN = 0.05;
double REGULAR_SERVICE = 10.00;
double REGULAR_OVERTIME_MIN = 0.20;
int acctNumber;
double premiumDayMin;
double premiumNightMin;
double bill = 0.0;
double minutes;
String name;
String premium = "PREMIUM";
String regular = "REGULAR";
System.out.println("What is the Account Number? ");
acctNumber = console.nextInt();
System.out.println("What is the Customer Name? ");
name = console.next();
System.out.println("Is the Service Code Premium or Regular? ");
String strService = console.next();
String strServiceCAP = strService.toUpperCase();
if(strServiceCAP.compareTo(premium) == 0)
{
System.out.println("How many Day Minutes were used? ");
premiumDayMin = console.nextDouble();
System.out.println("How many Night Minutes were used? ");
premiumNightMin = console.nextDouble();
if(premiumDayMin <0 && premiumNightMin <0)
{
System.out.println("Minutes cannot be less than 0 ");
}
else if(premiumDayMin <= 75 && premiumNightMin <= 100)
{
bill = PREMIUM_SERVICE;
}
else
{
bill = PREMIUM_SERVICE + (premiumDayMin - 75) * PREMIUM_DAY_OVERTIME_MIN + (premiumNightMin - 100)
* PREMIUM_NIGHT_OVERTIME_MIN;
}
minutes = premiumDayMin + premiumNightMin;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Premium Service Used (Day): " + premiumDayMin);
System.out.println("Minutes Premium Service Used (Night): " + premiumNightMin);
System.out.println("Amount Due: " + bill); // I get an error here stating, "The local variable 'bill' may not have been initialized".
}
else if(strServiceCAP.compareTo(regular) == 0)
{
System.out.println("How many minutes were used? ");
minutes = console.nextDouble();
bill = REGULAR_SERVICE + (minutes - 50) * REGULAR_OVERTIME_MIN;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Regular Service Used: " + minutes);
System.out.println("Amount Due: " + bill); // I DO NOT receive an error message here.
}
else
{
System.out.println("Invalid Service Type");
}
} // End of main
}
I'm not sure why it gets this error, but try initialising bill as 0.00 when you declare the variable.
Also,
if(premiumDayMin <0 && premiumNightMin <0)
should probably be changed to
if(premiumDayMin <0 || premiumNightMin <0)
Because you want to make sure that either minutes is not less then zero. You're program should then probably handle this error, because the rest of the program still executes. But maybe you're getting on to that :-P.
I don't recall what I did to stop getting an error message (sorry) but I removed the code if(premiumDayMin <0 && premiumNightMin <0) and replaced it with if(premiumDayMin <= 75 && premiumNightMin <= 100) to stop the code from being redundant. That may have fixed things. I also added another else if to clean the logic up further.
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.");
}