Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am having an issue with my homework assignment. When the program runs it keeps asking the user to enter the dealers twice instead of once, also when try to calculate to total commission it wrong, and also total sales can't get it to run.
Sales
commission
$1 - $5,000
8%
More than $5,000 to $15,000
15%
More than $15,000
20%
Problem:
Write a method to input and return the number of dealers. Perform the appropriate data validation here.
Write a method to gather the required input data. Perform the appropriate data validation here.
Write a method to calculate the commission array.
Write a method to calculate and return total sales for the dealership. Totals sales does not include the commission.
Write a method to calculate and return average sales for the dealership. The average sales value does not include the commission.
Write a method to calculate and return the total commission for the dealership.
Write a method to display the dealer name and amount of sales and the amount of commission for all dealers in a tabular format.
Write a method that accepts the name of a dealer as its parameter and returns the amount of commission for the given dealer. If the given name does not exist, issue an error message.
In your main method, make sure to call your methods to perform the operations. MAKE sure to display all the calculated data returned by your methods. For example, the totals and averages must be displayed, so the answers could be checked. Make output descriptive and provide 2 digits after the decimal point for all monetary values.
public static void main(String[] args) {
// TODO Auto-generated method stub
int d = dealers();
int [] numberDealers = new int [dealers()];
String [] employeeInfo = new String[numberDealers.length];
dealerInfo(employeeInfo.length);
getCommission(d);
//dealerTotalSales(employeeInfo.length);
}
//Method to get number of dealers from user input
public static int dealers() {
Scanner input = new Scanner(System.in); // Scanner for user input
System.out.println("Enter the number of dealears: ");
int numberDealers = input.nextInt();//Read user input
//Check to see if user is in range
//While not in range display error message and ask for input again
while(numberDealers < 0 || numberDealers > 20)
{
System.out.println("Invalid number, Please enter a number dealers
from 0 - 20!");
numberDealers = input.nextInt();
}
return numberDealers; //Return number of Dealers
}
public static void dealerInfo(int dealer) {
Scanner input = new Scanner(System.in); // Scanner for user input
String[] dealersName = new String [dealer];
double[] dealerSales = new double [dealer];
for (int i = 0; i < dealer; i++)
{
System.out.println("\nEnter the name of dealer: ");
dealersName[i] = input.next();
System.out.println("\nEnter the sales for dealer: ");
dealerSales[i] = input.nextDouble();
System.out.println("Name " + "Sales");
System.out.println(dealersName[i] + " " + dealerSales[i]);
}
}
public static void getCommission( int totalSales) {
double commission = 0.0;
double commissionRate ;
if( totalSales >0 && totalSales < 5000) {
commission = 0.10;
//System.out.print(commission);
}else if(totalSales < 15000 ){
commission = 0.15;
//System.out.print(commission);
}else {
commission = 0.20;
//System.out.print(commission);
}
commissionRate = commission + totalSales;
System.out.println("\n"+commissionRate );
}
public static double dealerTotalSales(int[] numDealers)
{
double totalSales = 0.0;
for (int i = 0; i < numDealers.length; i++) {
totalSales = totalSales + numDealers[i];
}
return totalSales;
}
}
The reason its asking you to enter the number of dealers two times is because you are calling the dealers() function twice in your main function. you can solve this by replacing
int [] numberDealers = new int [dealers()];
with
int [] numberDealers = new int [d];
Related
I am sure this is a dumb question but i have been at it for quite a bit.. I am trying to create a java program that calculates compound interest based off a user input of years and amount of money. But i keep getting an error that a void method cannot return a value. So i switch the method to a double because thats what will be returned, but than it tells me that a double method must return a double. Even tho im returning a double in the loop... Please help
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.00");
**strong text**
Scanner reader = new Scanner(System.in); //creates scanner
System.out.println("Enter number of years until retirement: "); //asks user to input number of years until retirement
int Years = reader.nextInt();
if (Years <= 0) {
System.out.println("Please enter a valid number"); //if the number of years was invalid, exits the program and asks to enter a valid number
System.exit(0);
}
System.out.println("Enter amount of money able to save annually: "); //asks user how much money they can input
double MoneySaved = reader.nextInt();
reader.close(); //closes scanner
for(int i=0; i < Years; i++)
{
Total = MoneySaved * 1.05;
return Total;
}
System.out.println("You will have $" + df.format(TotalAmount) + " saved up by retirement");
}
}
change your for to this
Double total = 0;
for(int i=0; i < Years; i++) {
total += MoneySaved;
total *= 1.05;
}
System.out.println(total);
Make the method a double and change
double MoneySaved = reader.nextInt();
to
double MoneySaved = reader.nextDouble();
Also I do not see your declaration of 'Total'; make sure that is declared as a double.
First, main Java method must be void and void methods cannot return a value(even compiler tells you that), although you can use a return statement to break execution of the method and return to calling method.
So answering your question, you have to create method that returns double and then just prints it in your main method or do not return anything and just replace
return Total;
with
System.out.println("You will have $" + df.format(Total) + " saved up by retirement");
PS: it looks like you are new to Java, so for a start read some content about Java, for example offical oracle tutorial
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this main class
public class Hotel
{
Scanner scan = new Scanner(System.in);
Register[] items = new Register[15];
int count = 0;
public static void main(String[] args)
{
DecimalFormat fmt = new DecimalFormat("0.##");
Hotel run = new Hotel();
int quantity, sale,night;
Register deluxe = new Deluxe();
Register family = new Family();
Register suite = new Suite();
Scanner input = new Scanner(System.in);
System.out.println("Enter customer's name:");
String name = input.next();
run.enterItems();
if(run.count != 0)
{
System.out.println("\nHotel Reservation Payment");
System.out.println("============================");
System.out.println("Customer name: " + name);
deluxe.displayInfo(); //supposed to print the details
family.displayInfo(); //supposed to print the details
suite.displayInfo(); //supposed to print the details
System.out.println("The final total is RM" + fmt.format(run.calcTotal()));
}
else
{
System.out.println("No items entered.");
run.enterItems();
}
}
public double calcTotal()
{
double total = 0;
for(int i = 0;i<count;i++)
{
total += items[i].total();
}
return total;
}
that is supposed to return the value i put in in the scanner here in the enterItems() that is in the class as the main class
public void enterItems()
{
int type, quantity, sale,night;
double price;
............................
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
System.out.println("\nHow many night?");
night = scan.nextInt();
items[count] = new Deluxe(quantity,sale,night);
count++;
}
So this will pass to the class called Deluxe where i have this method called displayInfo()
public class Deluxe implements Register
{
int quantity,night;
double sale;
public Deluxe(){}
....................................
public double total()
{
double total, price = 200.0;
price = price*quantity*night;
total = price - (price * (sale/100));
total += total *.06;
return total;
}
public void displayInfo(){
if (quantity > 0){
System.out.println("Room Type : Deluxe Room");
System.out.println("Quantity: " +quantity);
System.out.println("Discount: " +sale);
}
}
}
the problem is, in checking for quantity > 0, it actually does not get any value that i put in in the scanner. It will always return 0 for quantity regardless what amount i put in.
But the calculation works fine. Calculation is to calculate how many (quantity) rooms book x night stay x the room's price.
The calculation is also in the same class as the displayInfo() which is in class Deluxe.
So i was wondering what did i do wrong here.
The quantity which you input here:
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
Goes into main(String[] args).quantity that's defined here:
public class Hotel
{
....
public static void main(String[] args)
{
...
int quantity, sale,night;
...
}
The quantity that you check here:
if (quantity > 0){...}
Is a different parameter - it's Deluxe.quantity and is defined here:
public class Deluxe implements Register
{
int quantity,night;
...
}
Those two parameters have no relation. If you want them both to be the same, you need to pass to class Deluxe the main(String[] args).quantity parameter. You can do this via your own constructor under Hotel.main(String[] args), like so:
DecimalFormat fmt = new DecimalFormat("0.##");
Hotel run = new Hotel();
int quantity, sale,night;
Register family = new Family();
Register suite = new Suite();
Scanner input = new Scanner(System.in);
System.out.println("Enter customer's name:");
String name = input.next();
quantity = run.enterItems();
Register deluxe = new Deluxe(quantity,0,0); // entering the default value for the other two parameters like the empty constructor would leave them.
if(run.count != 0)
{
System.out.println("\nHotel Reservation Payment");
System.out.println("============================");
System.out.println("Customer name: " + name);
deluxe.displayInfo(); //supposed to print the details
family.displayInfo(); //supposed to print the details
suite.displayInfo(); //supposed to print the details
System.out.println("The final total is RM" + fmt.format(run.calcTotal()));
}
else
{
System.out.println("No items entered.");
run.enterItems();
}
if you change your enterItems() function to return the quantity parameter you need, like so:
public int enterItems()
{
int type, quantity, sale,night;
double price;
.........
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
System.out.println("\nHow many night?");
night = scan.nextInt();
items[count] = new Deluxe(quantity,sale,night);
count++;
return quantity;
}
Notice, this solves this only for the quantity parameter. if you need more, you might need to return the Deluxe structure from enterItems(). Good luck!
I am new To Java please help me, my local variable can't take me methods parameters.
import javax.swing.*;
import java.util.*;
import java.io.*;
import java.text.DecimalFormat; //I can not get my local variables in my
// main to accept my methods parameters.
// This is my program.
public class AccountBank
{
public static void main (String[] args) throws IOException
{
// Calling in my Class
Accountclass BankAcc = new Accountclass();
// initialize both there variables in. order to use them in a for loop.
double depDrw = 0;// this are one of the variables that is giving me problems
double withDrw = 0; // this is the other that is giving me problems
double totalW = 0;
double totalD = 0;
// declaring all my variables
String name="";
double month;
double startBal;
// This section will greet and accept input by asking the user to enter the starting alance and set it in my class
// Greetings
JOptionPane.showMessageDialog(null,"Lets Get Started");
// receiving input for my name variable
name = JOptionPane.showInputDialog(null, "Please Enter Your Name Below: ");
// ask user for starting balance
startBal = Double.parseDouble(JOptionPane.showInputDialog("What Is The Starting Balance In Your Account:"));
// This will set the value in my class
BankAcc.setBal(startBal);
// ask user how many months has the account been active
month = Double.parseDouble(JOptionPane.showInputDialog("Months That Account Has Been Active:"));
// This section will accept input by asking the user to enter each amount deposited every month from the account set it in my class.
// This will be shown in the message box
depDrw = depositTotal(deposit); << // I am having trouble here it wont take my parameters variable which I created on the buttom. please help
// This will sum up every amount the user enters in the message box.
totalD += depDrw;
// This will set the value in my class
BankAcc.setdeposit(totalD);
// This section will accept input by asking the user to enter each amount withdrawn every month from the account and set it in my class
// This will be shown in the message box
withDrw = withdrawTotal(wit); // <<< I am having problem here this variable does not take the value of my methods parameter, which i created on the bottom of this page.
// This will sum up every amount the user enters in the message box.
totalW += withDrw;
// This will set the value in my class
BankAcc.setwithdraws(totalW);
//This section will display the " monthly interest rate, monthly interest earned, total amount deposited, total amount withdrawn, and the final balance of the account."
DecimalFormat formatter = new DecimalFormat("#0.0000");
DecimalFormat formatter2 = new DecimalFormat("#0.0");
DecimalFormat formatter3 = new DecimalFormat("#0.00");
//Get the calculations from the savings account class and display them.
JOptionPane.showMessageDialog(null," Account Name: " +name+"\n \n Your Monthly Interest Rate Is ..... "
+ formatter.format(BankAcc.monthInt())+"%" + "\n \n Your Monthly Interest Earned Was ..... $"
+ formatter2.format(BankAcc.GetInt()) + "\n \n Your Overall Amount With Deposited Was ..... $" + totalD +
" \n \n Your Overall Amount WithDrawn Was ..... $" + totalW + " \n \n Your Remaining Balance Is ..... $"
+ formatter3.format(BankAcc.getFinalbal()),"Results", JOptionPane.PLAIN_MESSAGE );
}
public static double depositTotal( String deposit)
throws IOException
{
double sales;
double totalDeposit = 0;
File file = new File ("deposits.txt");
Scanner inputfile = new Scanner(file);
while (inputfile.hasNextDouble());
{
sales = inputfile.nextDouble();
totalDeposit += sales;
}
inputfile.close();
return totalDeposit;
}
public static double withdrawTotal( String wit)
throws IOException
{
double sales;
double totalwithdraws = 0;
File file = new File ("withdraws.txt");
Scanner inputfile = new Scanner(file);
while (inputfile.hasNextDouble());
{
sales = inputfile.nextDouble();
totalwithdraws += sales;
}
inputfile.close();
return totalwithdraws;
}
Your while loop is
while (inputfile.hasNextDouble());
{
sales = inputfile.nextDouble();
totalDeposit += sales;
}
There shouldn't be a ; after the while (inputfile.hasNextDouble())
while (inputfile.hasNextDouble())
{
sales = inputfile.nextDouble();
totalDeposit += sales;
}
Similarly for other while loops, remove the ;
Change your method declaration so it doesn't receive any parameter. And because it's returning a double, you may store the value it returns in a double variable:
double deposit = depositTotal();
In your depositTotal() method:
public static double depositTotal() throws IOException {
...
}
So we have to make a mortgage calculation project where we have to ask the user to calculate again and now we have to make it so it prints out a error message every time the user enters a string value for any of the inputs. I thought I did it right but something strange happens every time I run it and I can't figure out why and I know it's something wrong with the Try-Catch blocks.
Here are my outputs: http://imgur.com/cbvwM5v
As you can see the third time i run the program I enter a "two" as the second input and it still did the calculations. Then, the third time I tried it, I entered a negative number then a "two" and everything worked the way I wanted it to. Then, the last time I ran it I put a positive number for the first input and it still did the calculations, anything you guys see that might be doing this? Also, I think I may have used the wrong exception, I'm not uite sure what it means, I just guessed. am I supposed to user NumberFormatException and there is also a line under nfe saying that the value is not being used.
Here's my code:
package MortgageCalculation2c;
import java.text.NumberFormat;
import java.util.Scanner;
/**
*
* #author Akira
*/
public class MortgageCalculation2c {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double loanAmount = 0;
double interestRate = 0;
double numberYears = 0;
double months;
double monthlyPayment;
double numerator;
double denominator;
double formula;
boolean userInput = true;
String answer = ("y");
while (userInput) {
try {
loanAmount = 0;
interestRate = 0;
numberYears = 0;
//prompt user for the loan amount
System.out.print("Enter the loan amount: ");
loanAmount = Double.parseDouble(in.nextLine());
//prompt the user for the interest rate
System.out.print("Enter the rate: ");
interestRate = Double.parseDouble(in.nextLine());
//prompt the user for thenumber of years
System.out.print("Enter the number of years: ");
numberYears = Double.parseDouble(in.nextLine());
} catch (NumberFormatException nfe) {
System.out.println("You must enter positive numerical data!");
}
//if the user enters a negative number print out a error message, if not, continue calculations
if ((loanAmount <= 0) || (interestRate <= 0) || (numberYears <= 0)) {
System.out.println("ALL NUMERICAL VALUES MUST BE POSITIVE!");
} else {
//convert the interest rate
interestRate = interestRate / 100 / 12;
//the number of years must be converted to months
months = numberYears * 12;
//numerator of the monthly payment formula
numerator = (Math.pow(1 + interestRate, months));
//denominator of the monthly payment formula
denominator = ((numerator)-1);
//the formula equals the numerator divided by the denominator
formula = ( numerator / denominator );
//monthly payment calculation
monthlyPayment = (interestRate * loanAmount * formula);
//sytem output
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
System.out.println("The monthly payment is: " + defaultFormat.format(monthlyPayment));
}
//prompt the user if they would like to calculate the program again.
System.out.println("Would you like to calculate again (y/n) : ");
//if the user enters "y" the program will run again and if the user enters anything else it ends
answer = in.nextLine();
answer = answer.toLowerCase();
if ( answer.equals("y")){
userInput = true; //tests the program if it needs to run again
}else{
break; //ends the program
}
}
}
}
Is there anything that you guys can see that might be the problem?
It seems you need continue in your catch block, so the program flow goes back to the loop.
...
} catch (NumberFormatException nfe) {
System.out.println("You must enter positive numerical data!");
continue; // <---------- here
}
...
If this is not a specific exercise in try-catch construct, it be would be better to use Scanner's method hasNextDouble() for validatiing and nextDouble for reading and converting the numbers.
It will look something like this:
//prompt user for the loan amount
loanAmount = enterPositiveDouble("Enter the loan amount: ")
//prompt the user for the interest rate
interestRate = enterPositiveDouble("Enter the rate: ");
//prompt the user for the number of years
numberYears = enterPositiveDouble("Enter the number of years: ");
and you will have a special static method enterPositiveDouble like following:
static void enterPositiveDouble(String prompt) {
Scanner in = new Scanner(System.in);
boolean ok = true;
double result = -1;
do {
System.out.print(prompt);
ok = (in.HasNextDouble() && (result = in.NextDouble()) > 0)
if ! ok
System.out.println("You must enter positive numerical data!");
} while (!ok);
}
The above is not an optimal code but just the illustration of a possible solution.
The assignment is:
Write a program that provides 20% discount for member who purchase any two books at XYZ bookstore. (Hint: Use constant variable to the 20% discount.)
I have done the coding, but cannot prompt book name, and then show the discounted price. Please see my coding below and modify it as your needs.
import java.util.Scanner;
public class Book_Discount {
public static void main(String args[]) {
public static final double d = 0.8;
Scanner input = new Scanner(System.in);
int purchases;
double discounted_price;
System.out.print("Enter value of purchases: ");
purchases = input.nextInt();
discounted_price = purchases * d; // Here discount calculation takes place
// Displays discounted price
System.out.println("Value of discounted price: " + discounted_price);
}
}
For prompting the book name as well, you write something like:
/* Promt how many books */
System.out.print("How many books? ");
int bookCount = scanner.nextInt();
scanner.nextLine(); // finish the line...
double totalPrice = 0.0d; // create a counter for the total price
/* Ask for each book the name and price */
for (int i = 0; i < bookCount; ++i)
{
System.out.print("Name of the book? ");
String name = scanner.nextLine(); // get the name
System.out.print("Price of the book? ");
double price = scanner.nextDouble(); // get the price
scanner.nextLine(); // finish the line
totalPrice += price; // add the price to the counter
}
/* If you bought more than 1 book, you get discount */
if (bookCount >= 2)
{
totalPrice *= 0.8d;
}
/* Print the resulting price */
System.out.printf("Total price to pay: %.2f%n", totalPrice);