I found this Java exercise :
Create a class Sales that has TotalSales (double) , Commission (double),
Commissi onRate (double), and NoOfItems (integer).
write a java application that asks the user to enter the Total Sales and the number of items then calculates the commission and prints it out.
The commission rate should be as following:
Condition :
Less than 500, commissionRate is 0
Greater than or equal 500 or Number of Items >= 5, commission rate is 5%.
Grater than or equal 1000 or Number of items >=10, commission rate is 10%
..
I wrote this code:
Main Class :
import java.util.Scanner;
public class testSales {
public static void main(String[] args) {
Sales s1 = new Sales();
Scanner get = new Scanner(System.in);
System.out.println("Enter total Sales");
s1.totalSale = get.nextDouble();
System.out.println("Enter number of Items");
s1.NoOfItems = get.nextInt();
if(s1.totalSale < 500){
s1.commission = s1.commissionRate = 0;
}
else if(s1.totalSale >= 500 && s1.totalSale <= 999 || s1.NoOfItems >= 5 && s1.NoOfItems <=9){
s1.commission = s1.commissionRate = s1.totalSale * 5 / 100;
}else if(s1.totalSale >= 1000 || s1.NoOfItems >=10) {
s1.commission = s1.commissionRate = s1.totalSale *10/100;
}
System.out.println(s1.commission);
}
}
One problem in your code is the case where NoOfItems > 5 but totalSale < 500. For this case, the commission will incorrectly be set to 0 because the first if statement eats it.
Please try to be more specific with your question. "this doesn't work and I don't know why" is not easy to help with.
Aside from the point brought up by HedonicHedgehog, there are a few other things to consider:
The sales class only has two global variables, which corresponds to the information entered by the user. The other two fields, commission and commissionRate, are calculated values. Therefore, there is no need to create variables for them. Just add to the sales class accessor methods (getters) that return these values. For example, below is my getCommission() method:
public double getCommission()
{
return totalSales * getCommissionRate();
}
Of course, you can see this method is dependent upon the getCommissionRate() method. Because there is a gap on your requirements with total items, I am ignoring it for now:
public double getCommissionRate()
{
if (totalSales < 500)
return 0;
if(totalSales < 1000)
return .05;
else
return 0.1;
}
Alternatively, you could create a LOCAL commission variable, and set the value before returning it. It is a good programming practice to limit the scope of your variables. In this case, there is not a good reason to have a global commission or commissionRate variables.
Lastly, your test class is simplified because all you need to do is to prompt the user for the two needed fields, and it simply spits out the output because the Sales class provides the calculation needed to figure out the rest:
public static void main(String[] args)
{
Sales s1 = new Sales();
Scanner input = new Scanner(System.in);
System.out.print("Enter total Sales");
s1.setTotalSales(input.nextDouble());
System.out.print("Enter number of Items: ");
s1.setNumOfItems(input.nextInt());
System.out.printf("$%.2f", s1.getCommission());
input.close();
}
I used the printf() method to format the output string. The following is a sample run:
Enter total Sales: 503.45
Enter number of Items: 5
$25.17
Enter total Sales: 1003.67
Enter number of Items: 19
$100.37
Enter total Sales: 45.00
Enter number of Items: 19
$0.00
Remember that this example ignores the number of items because of the reasons already mentioned. Once you figure out what needs to be done to cover of the gap in the requirements, you can modify this code to do the rest. Also remember that your Sales class only requires two fields: totalSales and numOfItems. The other to components (commission, and commissionRate) are calculated; therefore, no global variable or setter methods needed. Just the two getter methods I provided.
Related
I'm writing a program for buying tickets. So far this is my code.
package prog;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Scanner;
public class assign {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Which type of ticket do you require stand or terrace?");
char tickType=sc.next().charAt(0);
System.out.println("How many tickets do you require?");
byte amount=sc.nextByte();
if (amount<5)
System.out.println("How many tickets for students?");
byte stud=sc.nextByte();
if (amount>=5)
System.out.println("You are entitled to a 12% discount.");
else if (stud>0)
System.out.println("discount will be 10%");
else
System.out.println("You are not entitled to a discount");
if (tickType=='S'||tickType=='s')
System.out.println("Ticket cost is\t "+amount*20.00);
else
System.out.println("Ticket cost is\t"+(amount*15.00));
double stand= amount*20.00;
double terrace= amount*15.00;
//VAT is 23%
When I get to
System.out.println("How many tickets do you require?");
byte amount=sc.nextByte();
if I enter 5 or a higher number I have to enter it twice rather than once can somebody tell me why this is happening please?
You have a flaw in the logic: if amount is less than five, then you print "How many tickets for students?", but then read the value even if amount is greater or equal to five.
The best solution would be to declare byte stud = 0; before if (amount < 5), and then correct the if statement to include two lines:
byte stud = 0;
if (amount < 5) {
System.out.println(...);
stud = sc.nextByte()
}
This way, you read the value for stud only if amount is less than 5.
You must be entering first value greater than 5. In this scenario it will not pass the condition if(amount<5) thus not printing s.o.p and expecting input because of next line which is byte stud=sc.nextByte();
I am super new to Java (4 days) and have never really coded anything except SQL databases and some simple java script before. I am building a sales commission calculator with a special policy that adjusts the amount of commission made based on an annual sales amount tier system (<=96,000, >96,000<=120,000 and >120,000).
I have that completed. . .What I need now is a way to use a second class(a second class is required ) to create an array that takes the output or input to/from the user and shows the user the potential money he/she could have made if his or her sales were at "X" in increments of 5,000 up to 50% of the user input for total sales. Here is the code I have so far: (I know my SystemOutTest class was in bad form sorry)
/**
*
* #author Wudkong
*/
import java.util.Scanner;
public class SystemOutTest {
Potentialwagechart Potentialwagechart;
public SystemOutTest(Potentialwagechart Potentialwagechart) {
this.Potentialwagechart = Potentialwagechart;
}
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) {
// main method for mathematics
Scanner input; // determines the method for the scanner
input = new Scanner(System.in); // creates an instance of scanner
int salary; // creates variables to be used later
int totalSales;
double commissionPercent;
double totalPay;
double commission;
salary = 50000; // defines a variable to a specific value for annual
// salary
System.out.print("enter annual sales amount please: ");
/**
* asks the user for the amount sold for the year
*/
totalSales = input.nextInt();
/**
* creates dialogue box for user to enter the annual sales amount
*/
commissionPercent = .15; // defines received total from sales data
if (totalSales <= 120000 * .8) {
commissionPercent = 0;
} else if (totalSales > 120000) {
commissionPercent = .1875;
;
} else
commissionPercent = .15;
{
commission = totalSales * commissionPercent;
/**
* Uses user defined data and commission percentage to create a
* value for total commission amount
*/
totalPay = commission + salary; // adds totals together
System.out.printf("Total annual pay is %.2f ", totalPay);
/**
* this uses an output stream to report to the user of the result of
* the method with just two decimal places showing.
*/
}
}
}
I would like to start the next class here but I am willing to take advice on just about anything. I know my code is sloppy and I do not know the best way to do this next part. I think I can build an array from a constant object just not an object that needs to be acquired from the user first. I also do not know how to make my classes communicate in the best way. I tried creating a reference to my second class in my first class and vice-versa but without the array or the object reference in place I can't test those links. Any help here is appreciated! I don't know if a get/set method can work or if I need to reference the output instead of the user input to create the array output plus 5,000 and the new potential wage on the side for x spaces. . ?
My program needs to allow the user to input an employee's name and total annual sales. When the user is finished adding employees to the array, the program should determine which employee had the highest sales and which had the lowest sales. It should then print out the difference between the two numbers.
In my code below, I have a totalPay class that holds the annual sales input by the user (it includes other variables and methods from a previous assignment that are not used here). The salesPerson class holds the employee's name and totalPay object, which includes their annual sales. (I realize this is overcomplicated, but I'm modifying my previous assignment rather than starting from scratch.)
When I run this code, it allows me to enter the name and sales, but when I enter "yes or no" to add another employee, it crashes and tells me there is a NullPointerException on line 58, noted in the code.
I've ran the debugger (without any breakpoints) and it just stops at line 46, noted in the code. It doesn't give an error message, it just doesn't update that variable and my "step into" buttons for the debugger grey out and I can't click them anymore. (I'm using NetBeans, if that's relevant.)
Any ideas would be much appreciated!
EDIT: Here is the output and error message.
Name? captain America
Input annual sales: 80
Add another employee? yes or no
no
Exception in thread "main" java.lang.NullPointerException at commission.Commission.main(Commission.java:58)
package commission;
//Commicaion calulator
import java.util.Scanner;
public class Commission
{
public static void main(String args [])
{
salesPerson[] emps = new salesPerson[10]; //Employee Array
String cont = "yes";
String n="";
double s=0;
int i=0;
salesPerson high = new salesPerson();
salesPerson low = new salesPerson();
// scanner object for input
Scanner keyboard = new Scanner(System.in);
//Enter in employee name
while (cont == "yes"){
System.out.print("Name? ");
n = keyboard.nextLine();
emps[i] = new salesPerson();
emps[i].setName(n);
//Loop of yes or no entering more employees
//If yes add another name if no continue with total Commision
//Enter in the sales amount of commistion
System.out.print("Input annual sales: ");
s=keyboard.nextDouble();
emps[i].pay.annual = s;
System.out.println("Add another employee? yes or no ");
keyboard.nextLine();
cont = keyboard.next(); //Line 46: Debugger stops here.
if (cont =="yes")
i++;
if (i==9){
System.out.println("You have reached the maximum number of employees.");
cont = "no";
}
}
i=0;
for (i=0; i<emps.length; i++){
if (emps[i].pay.annual > high.pay.annual) //Line 58: It claims the error is here.
high = emps[i];
if (emps[i].pay.annual < low.pay.annual)
low = emps[i];
}
double diff = high.pay.annual - low.pay.annual;
System.out.println("Employee "+low.getName()+" needs to earn "+diff+" more to match Employee "+high.getName());
// Output table for composation with increments of $5000
// int tempAnnual =(int) pay.annual;
// for (i=tempAnnual; i<= pay.annual; i+=5000)
// System.out.println(i+" "+ pay.getReward(i));
}
public static class totalPay
{
double salary=50000.0; //Yearly earned 50000 yr fixed income
double bonusRate1=.05; //bounus commission rate of 5% per sale
double commission; //Commission earned after a sale
double annual; //Sales inputted
double reward; // Yearly pay with bonus
double bonusRate2= bonusRate1 + 1.15 ; // Sales target starts at 80%
public double getReward(double annual)
{
double rate;
if (annual < 80000)
rate=0;
else if ((annual >= 80000) || (annual < 100000 ))
rate=bonusRate1;
else
rate=bonusRate2;
commission = annual * rate;
reward=salary + commission;
return reward;
}
}
public static class salesPerson
{
String name; //Employee Name
totalPay pay = new totalPay();
public void setName(String n) //Name
{
name=n;
}
public String getName()
{
return name;
}
}
}
You create this array of max size 10:
salesPerson[] emps = new salesPerson[10];
but only create and assign an object reference for each SalesPerson object entered. Since you only enter 1 name, only the 1st entry in the array is valid, then remaining 9 are null. You then attempt to iterate through the entire array (emps.length is 10 ):
for (i=0; i<emps.length; i++){
if (emps[i].pay.annual > high.pay.annual)
which leads to the NPE when indexing the first null reference. You need to change your loop to something like:
int numEntered = i; //last increment
for (i=0; i< numEnetered; i++){
if (emps[i].pay.annual > high.pay.annual)
It stops the debugger because it waits for your input using the keyboard. If you type the input and hit enter, the debugger will continue from there on.
By the way, your should read up on naming conventions and coding best practices for java
Your debugger is stopped because it's blocked on input coming in from the Scanner. This is specified in the documentation:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
That aside, you're fortunate to have entered that code block at all. You're comparing Strings incorrectly, so at a glance it'd look like you wouldn't enter that loop except under certain special circumstances. This is also the reason that your NPE occurs; you're initializing elements of your array under false pretenses (== with a String), so:
You may never initialize anything
You may only initialize the first thing (if (cont =="yes"))
I've only gone over a few of the high points, but for the most part, the blocking IO is why your debugger has stopped. The other errors may become easier to see once you start using .equals, but I'd encourage you to get an in-person code review with a classmate, tutor, or TA. There are a lot of misconceptions strewn about your code here which will make it harder to debug or fix later.
This is my first post and I have been searching google and stack overflow for the past 24 hours and can not seem to pin down my problem.
I am creating a simple square root program. For the input section I start a 'while' loop. I need it to compare two conditions.
1. is the input a number
2. is the input a number over ten.
I was successful in creating the original program, however I ran into a small problem while debugging. When I put in a vary large decimal or number I would get a run time error.
I discovered that I could use BigDecimal() to solve this problem.
However I am now running into a logic error that I cannot solve no matter how many times I search the internet.
The two conditions that I use in the while loop are:
while (!scan.hasNextBigDecimal() || (inputNumberBig.compareTo(SENTINAL)>0))
This will make sure that there is a BigDecimal, but will not make sure that the input number is over ten.
Here is the whole program
import java.math.BigDecimal;
import java.util.Scanner;
/**
#author Mike
*/
public class SquareRootingWithoutBigDecimal
{
public static void main( String [] args )
{
Scanner scan = new Scanner(System.in);
double inputNumber = 0.00;
double rootedNumber = inputNumber;
BigDecimal inputNumberBig = new BigDecimal(0.00);
BigDecimal SENTINAL = new BigDecimal(10.00);
String garbage;
double garbageD = 0.00;
System.out.println("Please Enter a number to be Square rooted"
+ "\nThe number must be 10 or greater ");
while (!scan.hasNextBigDecimal() || (inputNumberBig.compareTo(SENTINAL)>0))
{
garbage = scan.nextLine();
System.out.println("Please Enter a number to be Square rooted"
+ "\nThe number must be 10 or greater ");
}
inputNumberBig = scan.nextBigDecimal();
inputNumber = inputNumberBig.doubleValue();
rootedNumber = inputNumber;
do
{
rootedNumber = Math.sqrt(rootedNumber);
System.out.println(rootedNumber);
} while (rootedNumber >= 1.01 );
}
Any and all help is much appreciated.
-Mike
inputNumberBig = scan.nextBigDecimal();
inputNumber = inputNumberBig.doubleValue();
These HAVE to go before you while loop for your logic to work.
Also,
while (!scan.hasNextBigDecimal() || (inputNumberBig.compareTo(SENTINAL)>0))
I could see this causing a problem. You should use && instead of ||
Let me first make it clear that this is for an assignment. I'm very new to programming so all guidance is greatly appreciated. The program I have to calculate is a parking fee charge for a $2.00 minimum for 3 hrs or less, .50 cents per additional hr, and charge is capped at $10/ per 24 hr period. Program must display most recent customer charge as well as running total. Constants must be initialized, Math.ceil must be used, and method calculateCharges must be used to solve each cust's charge. I get uber errors when I attempt to run this program, and you'll probably laugh when you see it, but where have I erred? I'm not looking for the answer to be handed to me, just looking for the logic behind how to get to the correctly written program. Please help!
package Parking;
import java.util.Scanner;
public class parking
{
private static final double THREE_HOURS = 2.00;
private static final double PER_HOUR_COST = .50;
private static final double WHOLE_DAY_COST = 10.00;
public static void main (String [] args)
{
double hoursParked = 0;
double cumulativeCharges = 0;
double storage1 = 0;
double storage2 = 0;
Scanner input = new Scanner(System.in);
System.out.print("\nThis program displays the charge for the most recent customer");
System.out.print(" as well as the running total of yesterday's receipts\n");
do
{ System.out.printf("Enter an number between 1-24 for hours parked in garage or -1 to quit:");
hoursParked = input.nextDouble ();
}
while((hoursParked > 0)&&(hoursParked <= 24)&&(hoursParked != -1));
if( hoursParked <= 3)
System.out.printf("Most recent customer's charge was: %.2f\n" , THREE_HOURS);
storage1 += THREE_HOURS;
if(hoursParked >= 18.01)
System.out.printf("Most recent customer's charge was:%.2f\n" , WHOLE_DAY_COST);
storage2 += WHOLE_DAY_COST;
double result = calculateCharges(hoursParked * PER_HOUR_COST);
System.out.printf("Most recent customer charge was:%.2f\n" , result);
cumulativeCharges = storage1 + storage2;
System.out.printf("Running total of yesterday's receipts is:%.2f\n" , cumulativeCharges);
} // end main
public static double calculateCharges (double hoursParked)
{
Math.ceil(hoursParked);
double total = hoursParked * PER_HOUR_COST;
return total;
} // end method calculateCharges
} // end class parking
In your while condition, the third condition is useless because if the value is positive, that necessarily means it is different than -1.
In your function you want to calculate the cost of parking time but you give as parameter a cost instead of a number of hours when you call your function. Is that normal? With that you will calculate the cost of the cost instead of the cost corresponding to a number of hours.
public static double calculateCharges (double hoursParked)
and
double result = calculateCharges(hoursParked * PER_HOUR_COST);
There's a couple things here.
Your while condition is checked at the end of the do loop, it is what allows you to break after reading hoursParked. Thus, the only way you are going to reach the code outside of the do loop (after the while), is if hoursParked is -1.
Secondly, when you do not have braces for your if conditions, you are only executing the first line after it, aka. the System.out.print's. Therefore, your first if condition will execute (printing the string), then storing 2.00 in storage1. Similarly, the second if condition will execute (printing the string), then storing 10.00 in storage2.
Because hoursParked is always -1, you are passing in (-1 * .5) to calculateCharges. You are not storing the result of Math.ceil() so it effectively does nothing. You are then returning (-.5 * .5) = -.25.
cumulativeCharges is just adding 2 + 10 in every case.
Suggestions - make sure you are encapsulating the code you want to execute inside the do loop, and only break after you have done your calculations on hoursParked.