how do i calculate ranges of numbers using array? - java

my assignment is simple really. someone enter a number for their income, if its under 9000, its taxed at 10%, over that, its 15% etc.
but then one of the requirements says "you will organize the income ranges as an array in each method and select an array record to compute specific tax in a tax bracket"
how would that work? doesn't array only take specific values and not ranges of values??
this is my code so far
public static int calcTax(int status, int income)
{
if (status == 0)
{
return singleFiling(income);
}
if (status == 1)
{
return jointFiling(income);
}
if (status == 2)
{
return headFiling(income);
}
else
System.out.println("Error: invalid status. Enter a number between 0 to 2 only.");
return income;
}
static int ninek = 9075;
static int thrirtysixk = 36900;
static int eightyninek = 89350;
static int oneeightysixk = 186350;
static int fourofivek = 405100;
static int fourosixk = 406750;
static int eighteenk = 18150;
static int seventythreek = 73800;
static int onefortyeightk = 148850;
static int twotwentysixk = 226850;
static int fourfivesevenk = 457600;
static int twelveninefifty = 12950;
static int fourninek = 49400;
static int onetwentysevenk = 127550;
static int twoosixk = 206600;
static int fpurthreetwok = 432200;
static double tax = 0;
static int singleFiling(double userIncome)
{
if (userIncome >= 1 && userIncome <= ninek )
tax = userIncome * 0.10;
System.out.println("Your payable Federal tax is: " + tax);
return 0;
}
static int jointFiling(double userIncome)
{
if (userIncome >= 1 && userIncome <= oneeightysixk )
tax = userIncome * 0.10;
System.out.println("Your payable Federal tax is: " + tax);
return 0;
}
static int headFiling(double userIncome)
{
if (userIncome >= 1 && userIncome <= twelveninefifty )
tax = userIncome * 0.10;
System.out.println("Your payable Federal tax is: " + tax);
return 0;
}
}

Taking the comments into account, your code could look like this:
static int[] incomeLevel = new int[]{9075, 186350, 12950};
static double[] taxRate = new double[]{.1, .15, .2}
static double tax = 0.0;
public static int calcTax(int status, int income) {
if (status < 0 || status > 2) {
System.out.println("Error: invalid status. Enter a number between 0 to 2 only.")
return income;
}
if (income > 0 && income <= incomeLevel[status])
tax = income * taxRate[status];
System.out.println("Your payable Federal tax is: " + tax)
return 0;
}
Of course the other values for the income levels have to been added, same for the tax rates.
Instead of computing every value in another method, choosing by status, you can use the status as the array index. That has the advantage that only need the code once instead of three times but with some other values.
Now you only need to check if your status is in your wanted range.

Related

i compiled my java program and run in eclipse platform and also provide input but not got the output? There is any Logical Error in program [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
This is Selection Based Java Program. So in these program user have to provide the Vegetarian as V and Non-Vegetarian as N and it will take integer value for quantity and distance. So, when I saved and run the program it takes the value of the user parameter but didn't print the output I also check the errors in the eclipse editor.
#Program
'''
package demo;
import java.util.Scanner;
public class FoodCorner {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int vegCombo = 12;
int nonvegCombo = 15;
int totalCost = 0;
int charge = 0;
System.out.println("Enter the type of Food Item as Vegeterian 'V' and for Non-Vegeterian as 'N'");
String foodType = scan.nextLine();
System.out.println("Enter the Quantity of food Item");
int quantity = scan.nextInt();
System.out.println("Enter the Distance for delivery");
float distance = scan.nextFloat();
while(distance > 3) {
charge++;
distance = distance - 3;
}
if(distance > 0 && quantity >= 1) {
if(foodType == "V") {
totalCost = (vegCombo * quantity) + charge;
System.out.println("The total cost of your order is: "+totalCost);
}
else if(foodType == "N") {
totalCost = (nonvegCombo * quantity) + charge;
System.out.println("The total cost of your order is: "+totalCost);
}
}
else {
System.out.println("the bill amount is -1");
}
}
}
'''
Use below code snippet. Notice the line if("V".equals(foodType)) instead of if(foodType == "V").
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int vegCombo = 12;
int nonvegCombo = 15;
int totalCost = 0;
int charge = 0;
System.out.println("Enter the type of Food Item as Vegeterian 'V' and for Non-Vegeterian as 'N'");
String foodType = scan.nextLine();
System.out.println("Enter the Quantity of food Item");
int quantity = scan.nextInt();
System.out.println("Enter the Distance for delivery");
float distance = scan.nextFloat();
while(distance > 3) {
charge++;
distance = distance - 3;
}
if(distance > 0 && quantity >= 1) {
if("V".equals(foodType)) {
totalCost = (vegCombo * quantity) + charge;
System.out.println("The total cost of your order is: "+totalCost);
}
else if("N".equals(foodType)) {
totalCost = (nonvegCombo * quantity) + charge;
System.out.println("The total cost of your order is: "+totalCost);
}
}
else {
System.out.println("the bill amount is -1");
}
}

The programming storing quantities and writing else if statement to display the correct one

The program at the end will display the final estimation report. If the user only asked for one table, the output will display the final total estimate with the table as a singular. If the user asked for multiple tables, the output will display the number of tables and the total cost. If the user did not request any estimates at all, the program should display a message stating that.
It only displays "You did not estimate any tables...."
public class Table {
public static void main(String[] args) {
String material;
int tChoice;
int mChoice;
int numTable = 0;
double tableCost;
double total = 0;
double pLaminate = 0.125;
double pOak = 0.25;
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Tables are Us - Your One Stop Table Shop");
System.out.println("Mike - Master Table Builder");
boolean bFlag = true;
while (bFlag) {
double area = 0;
double length = -1;
double width = -1;
double diameter = -1;
double radius = -1;
do {
System.out.println("\n\nWhat shape of table do you wish to build?");
System.out.println("\t1. Rectangular");
System.out.println("\t2. Sqaure");
System.out.println("\t3. Circular");
System.out.println("\t4. End Program");
System.out.print("Enter menu entry: ");
tChoice = input.nextInt();
if (tChoice < 1 || tChoice > 4) {
System.out.println("Error - Invalid Entry. Please reenter a valid value.");
}
} while (tChoice < 1 || tChoice > 4);
if (tChoice == 1) {
while (length < 0) {
System.out.print("Enter the length of the table (in inches): ");
length = input.nextDouble();
if (length < 0) {
System.out.println("Error - the length must be greater than zero. Please reenter!!");
}
}
while (width < 0) {
System.out.print("Enter the width of the table (in inches): ");
width = input.nextDouble();
if (width < 0) {
System.out.println("Error - the width must be greater than zero. Please reenter!!");
}
}
area = length * width;
} else if (tChoice == 2) {
while (length < 0) {
System.out.print("Enter the length of the table (in inches): ");
length = input.nextDouble();
if (length < 0) {
System.out.println("Error - the length must be greater than zero. Please reenter!!");
}
}
area = length * length;
} else if (tChoice == 3) {
while (diameter < 0) {
System.out.print("Enter the diameter of the table (in inches): ");
diameter = input.nextDouble();
if (diameter < 0) {
System.out.println("Error - the diameter must be greater than zero. Please reenter!!");
}
}
radius = diameter / 2;
area = Math.PI * radius * radius;
} else if (tChoice == 4) {
if (numTable == 0) {
System.out.println("\nYou did not estimate any tables today!");
} else {
System.out.printf("The total cost of the " + numTable + "tables you estimated is $" + String.format("%.2f", total));
}
System.out.println("Thank you for using the table cost estimation program!");
System.out.println("GoodBye!!!");
input.close();
return;
}
do {
System.out.println("\nWhat type of material do you want to use?");
System.out.println("\t1. Laminate ($0.125 per square inch)");
System.out.println("\t2. Oak ($0.25 per square inch)");
System.out.print("Enter menu entry: ");
mChoice = input.nextInt();
if (mChoice < 1 || mChoice > 2) {
System.out.println("Error - Invalid Entry. Please reenter a valid value.");
}
} while (mChoice < 1 || mChoice > 2);
if (mChoice == 1) {
material = "Laminate";
tableCost = area * pLaminate;
} else {
material = "Oak";
tableCost = area * pOak;
}
System.out.println("\nOutput Report:");
System.out.printf("The area of table is " + String.format("%.2f", area) + " square inches");
System.out.printf("\nThe table will be made of " + material);
System.out.printf("\nThe cost of the table is $" + String.format("%.2f", tableCost));
total = total + tableCost;
total++;
}
input.close();
}
}
System.out.printf("The total cost of the %d tables you estimated is $%.2f%n", numTable, total);
Print-formatted needs a newline at the end %n.
Ensure that numTable is set.
public class Table {
public static void main(String[] args) {
System.out.println("Welcome to Tables are Us - Your One Stop Table Shop");
System.out.println("Mike - Master Table Builder");
int totalTables = 0;
double totalTableCost = 0;
Scanner scan = new Scanner(System.in);
scan.useLocale(Locale.ENGLISH);
while (true) {
int shapeMenuItem = getShapeMenuItem(scan);
if (shapeMenuItem == 4) {
printFinalResults(totalTables, totalTableCost);
return;
}
double area = getArea(scan, shapeMenuItem);
if (Double.isNaN(area))
System.err.println("Error - Invalid Entry. Please reenter a valid value.");
else {
int materialMenuItem = getMaterialMenuItem(scan);
double tableCost = area * getMaterialCost(materialMenuItem);
totalTableCost += tableCost;
totalTables++;
printReport(area, tableCost, materialMenuItem);
}
}
}
private static void printFinalResults(int numTable, double total) {
if (numTable == 0)
System.out.println("You did not estimate any tables today!");
else
System.out.format(Locale.ENGLISH, "\nThe total cost of the %d tables you estimated is $%.2f\n", numTable, total);
System.out.println("Thank you for using the table cost estimation program!");
System.out.println("GoodBye!!!");
}
private static void printReport(double area, double tableCost, int materialMenuItem) {
System.out.println("\nOutput Report:");
System.out.format(Locale.ENGLISH, "The area of table is %.2f square inches\n", area);
System.out.println("The table will be made of " + getMaterialName(materialMenuItem));
System.out.printf(Locale.ENGLISH, "The cost of the table is $%.2f\n", tableCost);
}
private static int getShapeMenuItem(Scanner scan) {
System.out.println("\n\nWhat shape of table do you wish to build?");
System.out.println("\t1. Rectangle");
System.out.println("\t2. Square");
System.out.println("\t3. Circle");
System.out.println("\t4. End Program");
System.out.print("Enter menu entry: ");
return scan.nextInt();
}
private static int getMaterialMenuItem(Scanner scan) {
while (true) {
System.out.println("\nWhat type of material do you want to use?");
System.out.println("\t1. Laminate ($0.125 per square inch)");
System.out.println("\t2. Oak ($0.25 per square inch)");
System.out.print("Enter menu entry: ");
int menu = scan.nextInt();
if (menu == 1 || menu == 2)
return menu;
System.err.println("Error - Invalid Entry. Please reenter a valid value.");
}
}
private static double getArea(Scanner scan, int shapeMenuItem) {
if (shapeMenuItem == 1)
return getRectangleArea(scan);
if (shapeMenuItem == 2)
return getSquareArea(scan);
if (shapeMenuItem == 3)
return getCircleArea(scan);
return Double.NaN;
}
private static double getRectangleArea(Scanner scan) {
double length = readDouble(scan, "Enter the length of the table (in inches): ");
double width = readDouble(scan, "Enter the width of the table (in inches): ");
return length * width;
}
private static double getSquareArea(Scanner scan) {
double length = readDouble(scan, "Enter the length of the table (in inches): ");
return length * length;
}
private static double getCircleArea(Scanner scan) {
double diameter = readDouble(scan, "Enter the diameter of the table (in inches): ");
double radius = diameter / 2;
return Math.PI * radius * radius;
}
private static String getMaterialName(int materialMenuItem) {
if (materialMenuItem == 1)
return "Laminate";
if (materialMenuItem == 2)
return "Oak";
return null;
}
private static double getMaterialCost(int materialMenuItem) {
if (materialMenuItem == 1)
return 0.125;
if (materialMenuItem == 2)
return 0.25;
return Double.NaN;
}
private static double readDouble(Scanner scan, String msg) {
while (true) {
System.out.print(msg);
double val = scan.nextDouble();
if (val > 0)
return val;
System.err.println("Error - Value must be greater than zero. Please reenter!!");
}
}
}

How can I find the highest, lowest, and average value of all test scores within my loop?

Good afternoon, or whenever you are reading this. I am trying to figure out how I can find the minimum, highest, and average of test scores that a user enters.
I have a loop that keeps track of a sentinel value, which in my case is 999. So when the user enters 999 it quits the loop. I also have some level of data validation by checking if the user entered over 100 or under 0 as their input. However, my question is, how can I implement a way to get this code to find the values I need for my user inputs. My code is as follows:
import java.util.Scanner;
public class TestScoreStatistics
{
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
int testScore;
double totalScore = 0;
final int QUIT = 999;
final String PROMPT = "Enter a test score >>> ";
int lowScore;
int highScore;
String scoreString = "";
int counter = 0;
System.out.print(PROMPT);
testScore = scn.nextInt();
while (testScore != QUIT)
{
if (testScore < 0 || testScore > 100 )
{
System.out.println("Incorect input field");
}
else
{
scoreString += testScore + " ";
counter++;
}
System.out.print(PROMPT);
testScore = scn.nextInt();
}
System.out.println(scoreString);
System.out.println(counter + " valid test score(s)");
}
}
While keeping your code pretty much the same, you could do it like this:
import java.util.Scanner;
public class TestScoreStatistics
{
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
int testScore;
double totalScore = 0;
final int QUIT = 999;
final String PROMPT = "Enter a test score >>> ";
int lowScore = 100; //setting the low score to the highest score possible
int highScore = 0; //setting the high score to the lowest score possible
String scoreString = "";
int counter = 0;
System.out.print(PROMPT);
testScore = scn.nextInt();
while (testScore != QUIT)
{
if (testScore < 0 || testScore > 100 )
{
System.out.println("Incorect input field");
}
else
{
scoreString += testScore + " ";
counter++;
//getting the new lowest score if the testScore is lower than lowScore
if(testScore < lowScore){
lowScore = testScore;
}
//getting the new highest score if the testScore is higher than highScore
if(testScore > highScore){
highScore = testScore;
}
totalScore += testScore; //adding up all the scores
}
System.out.print(PROMPT);
testScore = scn.nextInt();
}
double averageScore = totalScore / counter; //getting the average
}
This will check if the testScore is higher or lower than the highest and lowest scores. This program will also add all the scores together and divide them by the counter (which is how many tests there are) to get the average.
This is how I would do this.
// defines your prompt
private static String PROMPT = "Please enter the next number> ";
// validation in a separate method
private static int asInteger(String s)
{
try{
return Integer.parseInt(s);
}catch(Exception ex){return -1;}
}
// main method
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
System.out.print(PROMPT);
String line = scn.nextLine();
int N = 0;
double max = 0;
double min = Integer.MAX_VALUE;
double avg = 0;
while (line.length() == 0 || asInteger(line) != -1)
{
int i = asInteger(line);
max = java.lang.Math.max(max, i);
min = java.lang.Math.min(min, i);
avg += i;
N++;
// new prompt
System.out.print(PROMPT);
line = scn.nextLine();
}
System.out.println("max : " + max);
System.out.println("min : " + min);
System.out.println("avg : " + avg/N);
}
The validation method will (in its current implementation) allow any integer number to be entered. As soon as anything is entered that can not be converted into a number, it will return -1, which triggers a break from the main loop.
The main loop simply keeps track of the current running total (to calculate the average), and the maximum and minimum it has seen so far.
Once the loop is exited, these values are simply printed to System.out.
With minimal changes of your code:
public class Answer {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int testScore;
final int QUIT = 999;
final String PROMPT = "Enter a test score >>> ";
int maxScore = Integer.MIN_VALUE;
int minScore = Integer.MAX_VALUE;
double totalScore = 0;
double avgScore = 0.0;
int counter = 0;
System.out.print(PROMPT);
testScore = scn.nextInt();
while (testScore != QUIT) {
if (testScore < 0 || testScore > 100) {
System.out.println("Incorect input field");
} else {
counter++;
System.out.println("The number of scores you entered is " + counter);
//test for minimum
if(testScore < minScore) minScore = testScore;
System.out.println("Current minimum score = " + minScore);
//test for maximum
if(testScore > maxScore) maxScore = testScore;
System.out.println("Current maximum score = " + maxScore);
//calculate average
totalScore += testScore;
avgScore = totalScore / counter;
System.out.println("Current average score = " + avgScore);
}
System.out.print(PROMPT);
testScore = scn.nextInt();
}
}
}

Im writing a class called discount.java and i am having issues processing negative values for quantity and price

As I mentioned, I am writing a class called discount.java and TestDiscount.java; so far everything works but i am having issues getting the error message to display instead of the actual value when either quantity or price and negative values. Here is a little more info about the required output and what i have done so far:
The output must be of the form:
The quantity is: xx The unit price is: $xx.xx The discount is: $xx.xx
Or
The quantity is: -xx Quantity is negative. Cannot compute discount
Or
The quantity is: 150 The unit price is: -$15.00 The money is negative, cannot
compute discount amount
public class discount {
int quantity;
double price;
public static int NINETY_NINE = 99;
public static int TWENTY = 20;
private static int TEN = 10, FORTY_NINE = 49;
public static double TEN_PERCENT = 0.10, FIVE_PERCENT = 0.05,
TWO_PERCENT = 0.02, THREE_PERCENT = 0.03, ONE_PERCENT = 0.01 ;
private double discount;
// public static double discount_amount = discount * quantity * price;
discount(int quantity, double price)
{
double discount = 0;
//double d = discount;
this.quantity = quantity;
this.price = price;
}
boolean quantityOutOfRange()
{
return quantity < 0;
}
boolean priceOutOfRange()
{
return price < 0;
}
public double getDiscount()
{
return discount;
}
public int getQuantity()
{
return quantity;
}
public double getUnitPrice()
{
return price;
}
public void calculate()
{
if (quantity > NINETY_NINE)
{
if (price > TWENTY)
discount = TEN_PERCENT;
else if ( price > TEN)
discount = FIVE_PERCENT;
else
discount = TWO_PERCENT;
}
else if (quantity > FORTY_NINE)
{
// calculate discount
if (price > TWENTY)
discount = THREE_PERCENT;
else if ( price > TEN)
discount = TWO_PERCENT;
else
discount = ONE_PERCENT;
}
else
{
// calculate discount
if (price > TWENTY)
discount = TWO_PERCENT;
else if ( price > TEN)
discount = ONE_PERCENT;
else
discount = 1;
}
if (quantity < 0)
{
System.out.println("Quantity is negative. Cannot compute discount");
}
//double discount_amount = discount * quantity * price;
}
}
public class TestDiscount {
public static void main(String[] arg) {
String input = JOptionPane.showInputDialog("Enter the quantity desired "
+ ", and unit price "
+ "\n(Separated by spaces)");
Scanner in = new Scanner(input);
int quantity = in.nextInt();
double price = in.nextDouble();
discount current = new discount(quantity, price);
current.calculate();
System.out.println("\nDiscounts:\n");
System.out.println("The quantity is: " + current.getQuantity()+ "\tThe unit price is = $ " + current.getUnitPrice() +
"\tThe discount is = $ " + current.getQuantity()* current.getUnitPrice() * current.getDiscount());
System.exit(0) ;
}
}
create new method called like
public boolean validated() {
boolean ok = true;
if (quantity < 0)
{
System.out.println("Quantity is negative. Cannot compute
discount");
ok = false;
}
if (price< 0)
{
System.out.println("Price is negative. Cannot compute
discount");
ok = false;
}
return ok;
}
Then in main
discount current = new discount(quantity, price);
if (current.validated ()) {
current.calculate ();
}
In method Calculate first check for negative values
if (quantity < 0)
{
System.out.println("error message");
}
if (price < 0)
{
System.out.println("error message");
}

Java method returning incorrect values

I'm struggling learning to properly code methods in Java. I've looked at many examples and can't see what I'm doing wrong. I've got a main class called InvoiceApp which uses a class called Validator to screen input and then a class called Invoice which processes the user input. When InvoiceApp is run, the user inputs either 'r' or 'c' as the Customer Type, and a double value for "subtotal". The app creates an object of the Invoice class to use the getInvoice() method, which returns a formatted invoice.
The formatted invoice is returned, but with NULL value for the String and ZEROES for all the numbers (except that which the user input in the 1st place). The Invoice class is apparently not assigning values to the variables. I've done this many, many different ways and cannot get the thing to work.
Can anyone see what I've done wrong? Here is my code:
The InvoiceApp class:
import java.util.Scanner;
public class InvoiceApp
{
public static void main(String[] args)
{
// display a welcome message
System.out.println("Welcome to the Invoice Total Calculator");
System.out.println(); // print a blank line
Scanner sc = new Scanner(System.in);
String choice = "y";
while(choice.equalsIgnoreCase("y"))
{
// get user entries
String customerType = Validator.getString(sc,
"Enter customer type (r/c): ");
double subtotal = Validator.getDouble(sc,
"Enter subtotal: ", 0, 10000);
Invoice i;
i = new Invoice(customerType, subtotal);
System.out.println();
System.out.println(i.getInvoice());
System.out.println();
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
The Invoice class:
import java.text.NumberFormat;
public class Invoice {
private final String customerType;
private final double subtotal;
private double discountAmount;
private double discountPercent;
private double invoiceTotal;
private String sCustomerType;
public Invoice(String customerType, double subtotal){
this.customerType = customerType;
this.subtotal = subtotal;
}
public void setDiscountPercent(double discountPercent){
if (customerType.equalsIgnoreCase("r"))
{
if (subtotal >= 500)
discountPercent = .2;
else if (subtotal >= 250 && subtotal < 500)
discountPercent =.15;
else if (subtotal >= 100 && subtotal < 250)
discountPercent =.1;
else if (subtotal < 100)
discountPercent =.0;
}
else if (customerType.equalsIgnoreCase("c"))
{
discountPercent = .2;
}
else
{
discountPercent = .05;
}
}
public double getDiscountPercent(){
return discountPercent;
}
public void setDiscountAmount(double discountAmount){
discountAmount = subtotal * (getDiscountPercent());
}
public double getDiscountAmount(){
return discountAmount;
}
public void setInvoiceTotal(double invoiceTotal){
invoiceTotal = subtotal - (getDiscountAmount());
}
public double getInvoiceTotal(){
return invoiceTotal;
}
public void setCustomerType(String sCustomerType){
sCustomerType = "Unknown";
if (customerType.equalsIgnoreCase("r"))
sCustomerType = "Retail";
else if (customerType.equalsIgnoreCase("c"))
sCustomerType = "College";
}
public String getCustomerType(){
return sCustomerType;
}
public String getInvoice(){
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
sCustomerType = this.getCustomerType();
discountPercent = this.getDiscountPercent();
discountAmount = this.getDiscountAmount();
invoiceTotal = this.getInvoiceTotal();
// Create a string representation of the full invoice and return
String invoice = ("Subtotal: " + currency.format(subtotal) + "\n"
+ "Customer type: " + sCustomerType + "\n"
+ "Discount percent: " + percent.format(discountPercent)+ "\n"
+ "Discount amount: " + currency.format(discountAmount)+ "\n"
+ "Total: " + currency.format(invoiceTotal) + "\n");
return invoice;
}
}
The Validator class:
import java.util.Scanner;
public class Validator
{
public static String getString(Scanner sc, String prompt)
{
System.out.print(prompt);
String s = sc.next(); // read user entry
sc.nextLine(); // discard any other data entered on the line
return s;
}
public static int getInt(Scanner sc, String prompt)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextInt())
{
i = sc.nextInt();
isValid = true;
}
else
{
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i;
}
public static int getInt(Scanner sc, String prompt,
int min, int max)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println(
"Error! Number must be greater than " + min + ".");
else if (i >= max)
System.out.println(
"Error! Number must be less than " + max + ".");
else
isValid = true;
}
return i;
}
public static double getDouble(Scanner sc, String prompt)
{
double d = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextDouble())
{
d = sc.nextDouble();
isValid = true;
}
else
{
System.out.println("Error! Invalid decimal value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return d;
}
public static double getDouble(Scanner sc, String prompt,
double min, double max)
{
double d = 0;
boolean isValid = false;
while (isValid == false)
{
d = getDouble(sc, prompt);
if (d <= min)
System.out.println(
"Error! Number must be greater than " + min + ".");
else if (d >= max)
System.out.println(
"Error! Number must be less than " + max + ".");
else
isValid = true;
}
return d;
}
}
Thanks to anyone that can help
Thank you all. I removed the parameters from the setter methods and added this. to the constructors. Obviously, there are two major areas that I'm confused about:
What parameters are supposed to be in the set methods? I tried to insert the variables that the set methods actually use, but that didn't work either.
I thought get methods were simply used to return the values generated by the set methods. Since the setters are all void, they can't be directly used. Working examples I've seen are constructed similarly (however they actually work).
Here is what I changed in the Invoice class.
import java.text.NumberFormat;
public class Invoice {
private final String customerType;
private final double subtotal;
private double discountAmount;
private double discountPercent;
private double invoiceTotal;
private String sCustomerType;
public Invoice(String customerType, double subtotal){
this.customerType = customerType;
this.subtotal = subtotal;
}
public void setDiscountPercent(){
if (customerType.equalsIgnoreCase("r"))
{
if (subtotal >= 500)
this.discountPercent = .2;
else if (subtotal >= 250 && subtotal < 500)
this.discountPercent =.15;
else if (subtotal >= 100 && subtotal < 250)
this.discountPercent =.1;
else if (subtotal < 100)
this.discountPercent =.0;
}
else if (customerType.equalsIgnoreCase("c"))
{
this.discountPercent = .2;
}
else
{
this.discountPercent = .05;
}
}
public double getDiscountPercent(){
return this.discountPercent;
}
public void setDiscountAmount(){
this.discountAmount = subtotal * (getDiscountPercent());
}
public double getDiscountAmount(){
return this.discountAmount;
}
public void setInvoiceTotal(){
this.invoiceTotal = subtotal - (getDiscountAmount());
}
public double getInvoiceTotal(){
return this.invoiceTotal;
}
public void setCustomerType(){
this.sCustomerType = "Unknown";
if (customerType.equalsIgnoreCase("r"))
this.sCustomerType = "Retail";
else if (customerType.equalsIgnoreCase("c"))
this.sCustomerType = "College";
}
public String getCustomerType(){
return this.sCustomerType;
}
public String getInvoice(){
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
sCustomerType = this.getCustomerType();
discountPercent = this.getDiscountPercent();
discountAmount = this.getDiscountAmount();
invoiceTotal = this.getInvoiceTotal();
// Create a string representation of the full invoice and return
String invoice = ("Subtotal: " + currency.format(subtotal) + "\n"
+ "Customer type: " + sCustomerType + "\n"
+ "Discount percent: " + percent.format(discountPercent)+ "\n"
+ "Discount amount: " + currency.format(discountAmount)+ "\n"
+ "Total: " + currency.format(invoiceTotal) + "\n");
return invoice;
}
}
I GOT IT TO WORK, Thanks to you guys! Now I understand much more about set and get methods, as well as the this. keyword.
Here is the working Invoice class:
import java.text.NumberFormat;
public class Invoice {
private final String customerType;
private double subtotal;
private double discountAmount;
private double discountPercent;
private double invoiceTotal;
private String sCustomerType;
public Invoice(String customerType, double subtotal){
this.customerType = customerType;
this.subtotal = subtotal;
}
public void setSubtotal(double subtotal){
this.subtotal = subtotal;
}
public double getSubtotal(){
return subtotal;
}
public void setDiscountPercent(double discountPercent){
this.discountPercent = discountPercent;
}
public double getDiscountPercent(){
if (customerType.equalsIgnoreCase("r"))
{
if (subtotal >= 500)
discountPercent = .2;
else if (subtotal >= 250 && subtotal < 500)
discountPercent =.15;
else if (subtotal >= 100 && subtotal < 250)
discountPercent =.1;
else if (subtotal < 100)
discountPercent =.0;
}
else if (customerType.equalsIgnoreCase("c"))
{
discountPercent = .2;
}
else
{
discountPercent = .05;
}
return discountPercent;
}
public void setDiscountAmount(double discountAmount){
this.discountAmount = discountAmount;
}
public double getDiscountAmount(){
discountAmount = subtotal * (getDiscountPercent());
return discountAmount;
}
public void setInvoiceTotal(double invoiceTotal){
this.invoiceTotal = invoiceTotal;
}
public double getInvoiceTotal(){
invoiceTotal = subtotal - (getDiscountAmount());
return invoiceTotal;
}
public void setCustomerType(String sCustomerType){
this.sCustomerType = sCustomerType;
}
public String getCustomerType(){
sCustomerType = "Unknown";
if (customerType.equalsIgnoreCase("r"))
sCustomerType = "Retail";
else if (customerType.equalsIgnoreCase("c"))
sCustomerType = "College";
return sCustomerType;
}
public String getInvoice(){
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
// Create a string representation of the full invoice and return
String invoice = ("Subtotal: " + currency.format(getSubtotal()) + "\n"
+ "Customer type: " + getCustomerType() + "\n"
+ "Discount percent: " + percent.format(getDiscountPercent())+ "\n"
+ "Discount amount: " + currency.format(getDiscountAmount())+ "\n"
+ "Total: " + currency.format(getInvoiceTotal()) + "\n");
return invoice;
}
}
Thanks again!
You are hiding fields with method parameters in a number of places in your code, e.g.:
public void setDiscountPercent(double discountPercent){
...
if (subtotal >= 500)
discountPercent = .2;
...
Note that you have a field named discountPercent and a method parameter named discountPercent. It is the parameter variable that is being modified there, not the field. Either use this, e.g.:
public void setDiscountPercent(double discountPercent){
...
if (subtotal >= 500)
this.discountPercent = .2;
...
Or rename your method parameters to not conflict with fields.
You'll have to go through your code and find these, it happens in a few places, e.g. here's another in setDiscountAmount():
public void setDiscountAmount(double discountAmount){
discountAmount = subtotal * (getDiscountPercent());
}
Should be:
public void setDiscountAmount(double discountAmount){
this.discountAmount = subtotal * (getDiscountPercent());
}
Also, since you don't actually seem to be using those parameters in your methods anywhere, either a) you shouldn't pass them, or b) you meant to be using them somehow, but you are not.
Additionally, as MrTi points out in comments, you also don't seem to be calling the setters anywhere. You are (attempting to) initialize some of the values in the Invoice constructor, but you're not really finishing the job there.
As Erwin Bolwidt points out in comments, in general, you seem to be confused about the concepts of "getters" and "setters". In particular, your setters aren't really "setters" - and it doesn't really seem like you actually need them at all to begin with, as your intention seems to be to simply calculate all the values in the constructor then retrieve them later (e.g. you could just have getters, and perform the calculations either in the getters, or in the constructor). Check out this question for some good answers and links about the topic. Read through that, and it should give you a better handle on what you're trying to achieve here.

Categories