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.
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.
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.");
}
I am trying to validate the the user input, but I can't get it to work.
The user has to enter an amount of Revenue between 0-20,000, but not anything more than that.
In addition, the user must enter expenses between 1500-10000, but not anything more than that or less than that.
I also am trying to loop the code as well. I am asking the user if they have additional records they want to enter in or not, and I am counting how many times the record has been done.
Can anyone tell me what I am doing wrong and point me in the right direction?
Here is what I have so far:
import javax.swing.JOptionPane;
import java.io.*; // Access System.out
import java.util.Scanner;
public class RevenueScan
{
public static void main(String[] args)
{
// Declarations
Scanner in = new Scanner(System.in);
int productNumber;
float revenue;
float expenses;
double finalValue;
char repeat;
int counter = 0;
String input;
Scanner keyboard = new Scanner(System.in);
// Do Loop to run
do
{
// Pop up to advise the user the conditions that have to be met for inputs
System.out.println("Please ensure that your revenue is between 0 to 20,000.00 dollars."
+ "\nPlease ensure that your expenses are between 1,500.000 to 10,000.00 dollars.");
// Pop up to ask the user the values of the variables
System.out.println("Enter in a Product Number (or-1 to END)"
+ "\nEnter the Revenue"
+ "\nEnter the Expenses");
// Read in values
productNumber = in.nextInt();
revenue = in.nextFloat();
expenses = in.nextFloat();
//States the values entered by user
while (revenue < 0 || revenue > 20000 || expenses < 1500 || expenses > 10000);
{
System.out.println("You have entered in either an invalid revenue or expense. Please enter in valid numbers.");
{
System.out.println("Here is the product number you entered: " + productNumber + "."
+ "\nHere is the revenue you entered: " + revenue + "."
+ "\nHere are the expenses you entered: " + expenses + ".");
counter++;
//calculates final value
}
}
finalValue = revenue - expenses;
// Calculates final value and displays as net profit, loss or break even.
if (finalValue > 0)
{
System.out.println("You made a profit. Your net income is: " + finalValue);
}
else
if (finalValue == 0)
{
System.out.println("You broke even. Your revenue was " + revenue + " your expenses were " + expenses);
}
else
if (finalValue < 0)
{
System.out.println("You have not made any profit. Your net loss is: " + finalValue);
}
System.out.println("Number of records: " + counter);
//validate user input
System.out.println("Would you like to input more records?");
System.out.println("Enter 'Y' for yes or 'N' for no.");
input = keyboard.nextLine();
repeat = input.charAt(0);
}
while (repeat == 'Y' || repeat == 'y');
{
}
}
}
You have a ; after the while-statement, it shouldn't be there, otherwise the while-loop is empty, as opposed to containing the block following it.
while (revenue < 0 || revenue > 20000 || expenses < 1500 || expenses > 10000)
{
System.out.println("You have entered in either an invalid revenue or expense. Please enter in valid numbers.");
{
System.out.println("Here is the product number you entered: " + productNumber + "."
+ "\nHere is the revenue you entered: " + revenue + "."
+ "\nHere are the expenses you entered: " + expenses + ".");
counter++;
}
}
But once you fix this, the above block will just keep looping, since none of the values can change inside that loop.
Also, those inner brackets {} are somewhat pointless.
I recommend this:
if (revenue < 0 || revenue > 20000 || expenses < 1500 || expenses > 10000)
{
System.out.println("You have entered in either an invalid revenue or expense. Please enter in valid numbers.");
System.out.println("Here is the product number you entered: " + productNumber + "."
+ "\nHere is the revenue you entered: " + revenue + "."
+ "\nHere are the expenses you entered: " + expenses + ".");
counter++;
continue; // go to the start of the do-while loop
}
Then you also have to change:
char repeat;
to:
char repeat = 'Y';
otherwise it doesn't compile since continue still triggers the condition check, and repeat won't be initialized the first time, and Java doesn't allow this.
If you want to stick to a while-loop, put something like these lines in there:
// tell user to input values again
System.out.println("Enter in a Product Number (or-1 to END)"
+ "\nEnter the Revenue"
+ "\nEnter the Expenses");
// read in values
productNumber = in.nextInt();
revenue = in.nextFloat();
expenses = in.nextFloat();
This will allow the user to input new values until the conditions are met.
And the format of a do-while loop is:
do { ... }
while (...);
Not:
do { ... }
while (...) { ... }
So change:
while (repeat == 'Y' || repeat == 'y');
{
}
To:
while (repeat == 'Y' || repeat == 'y');
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