I'm struggeling a bit with arrays and user what's inside with loops. I have this question for example (ignore what's inside of the previewOrder method, i was trying stuff out):
public class Ex1_19 {
final static String NAMES[]= {"Spa reine 25 ","Bru plate 50","Bru pét 50",
"Pepsi","Spa orange", "Schweppes Tonic","Schweppes Agr","Ice Tea","Ice Tea Pêche",
"Jus d'orange Looza", "Cécémel", "Red Bull","Petit Expresso","Grand Expresso","Café décaféiné ",
"Lait Russe ","Thé et infusions","Irish Coffee ","French Coffee ","Cappuccino","Cécémel chaud",
"Passione Italiano","Amour Intense", "Rhumba Caliente ","Irish Kisses ","Cuvée Trolls 25",
"Cuvee Trolls 50","Ambrasse-Temps 25","Ambrasse-Temps 50 ","Brasse-Temps Cerises 25",
"Brasse-Temps Cerises 50","La Blanche Ste Waudru 25","Blanche Ste Waudru 50",
"Brasse-Temps citr 25","Brasse-Temps citr 50","Spaghetti Bolo ","Tagl Carbonara",
"Penne poulet baslc ","Tagl American","Tagl saum"};
final static double NETPRICES[]= {2.2, 2.3,3.9,2.2,2.2,2.6,2.6,2.6,2.6,2.6,2.6,4.5,2.2,2.2,2.2,2.5,2.5,7.0,7.0,2.8,2.8,6.2,6.2,6.2,6.2,
2.9,5.5,2.7,5.1,3.1,5.8,2.6,4.9,2.6,4.9,10.8,11.2,12.2,14.5,16.9};
public static void main(String[] args) {
int Order[][]={{3,2},{1,3},{12,4},{37,1},{36,3},{0,0},{0,0},{0,0}, {0,0}};
previewOrder(Order);
}
public static void previewOrder(int order[][]) {
int i = 0;
int j = 0;
while(i < order.length && j < order.length) {
System.out.println(NAMES[i]);
i++;
j++;
}
}
}
My result has to be something like this but with what's inside the "order" array:
Bru pét 50 3.9 2 7,80
Spa reine 25 2.2 3 6,60
Red Bull 4.5 4 18,00
Tagl Carbonara 11.2 1 11,20
Spaghetti Bolo 10.8 3 32,40
In my exercice I have to use a while loop and I have to put the order array in my method parameters. I can't figure out how to make them all communicate.
Sorry if this question has been answered somewhere else but I don't know how to search for it.
EDIT: I know that Orders does not use zero based index, but starts at 1. This is probably because "Order" is supposed to be a user entry. The first number of the array is like a drink number.
I wasn't very clear on the expected output.
Bru pét 50 (NAME[3]) 3.9 (NETPRICE[3]) 2 (Order[][2]) 7.80 NETPRICE[3] * Order[][2] and this for every occurence in Order
The Order array (btw: should be named order or orders) obviously contains references to ordered items and their amount. It's a two dimensional array, like a table with two columns.
Your expected output of "Bru pét 50 3.9 2 7,80", coming from Order[0] {3,2} indicates that the first element (Order[0][0]) is a reference to the items name (from NAMES) and the price (from NETPRICES). The second value of each "row" is the item amount (2) and finally there's the computed total.
For reasons unknown, Orders does not not use zero-based indexed, but starts at 1. So ORDER[0] having value {3,2} actually referes to NAMES[2] and NETPRICES[2]. This needs to be taken into account when picking the right item form NAMES and NETPRICES.
Anyhow: This is what your method could look like. You still need to tweak the output according to your needs.
public static void previewOrder(int order[][]) {
for (int i = 0; i < order.length; i++) {
int index = order[i][0] - 1;
if (index < 0 || index > NAMES.length || index > NETPRICES.length) {
continue;
}
String name = NAMES[order[i][0] - 1];
double price = NETPRICES[order[i][0] - 1];
int amount = order[i][1];
double total = amount * price;
System.out.println(
name + " " + price + " " + amount + " " + total
);
}
}
Try this.
public static void previewOrder(int order[][]) {
Stream.of(order)
.filter(x -> x[0] != 0)
.forEach(x -> {
String name = NAMES[x[0] - 1];
int unit = x[1];
double price = NETPRICES[x[0] - 1];
System.out.printf("%s %.1f %d %.2f%n",
name, price, unit, price * unit);
});
}
output:
Bru p?t 50 3.9 2 7.80
Spa reine 25 2.2 3 6.60
Red Bull 4.5 4 18.00
Tagl Carbonara 11.2 1 11.20
Spaghetti Bolo 10.8 3 32.40
or
public static void previewOrder(int order[][]) {
for (int[] row : order) {
if (row[0] == 0)
continue;
String name = NAMES[row[0] - 1];
int unit = row[1];
double price = NETPRICES[row[0] - 1];
System.out.printf("%s %.1f %d %.2f%n",
name, price, unit, price * unit);
}
}
When I see tightly coupled arrays, I think of creating a class.
public class Product {
String name;
double unitPrice;
public Product () {
name = "*** Unnamed Product ***";
unitPrice = 0.0;
}
public Product (String name, double unitPrice) {
this.name = name;
this.unitPrice = unitPrice;
}
public String getName () { return name; }
public double getPrice () { return unitPrice; }
public String toString () { return name + " # " + unitPrice + " ea.";}
}
Then, you can have one array where you previously had two:
public class Ex1_19 {
static final Product [] productList = {
new Product("Spa reine 25 ", 2.2),
new Product("Bru plate 50", 2.3),
new Product("Bru pét 50", 3.9),
new Product("Pepsi", 2.2),
new Product("Spa orange", 2.2),
new Product("Schweppes Tonic", 2.6),
new Product("Schweppes Agr", 2.6),
new Product("Ice Tea", 2.6)
// and so on
};
}
The preview order method, without formatted output, might look like this:
public static void previewOrder (int[][] order) {
double total = 0.0;
double itemCount = 0;
int lineNum = 0;
for (int i = 0; i < order.length; ++i) {
int row = order[i][0] - 1;
if (row < 0) {
break;
}
int qty = order [i][1];
double amt = productList [row].getPrice () * qty;
System.out.println (++lineNum + " " + productList[row].getName()
+ " " + productList[row].getPrice () + " " + qty
+ " " + amt);
itemCount += qty;
total += amt;
}
System.out.println ("===\nTotal: " + total + " for " + itemCount + " items.");
}
i've been puzzling over this for about 5 hours now, I just can't get the errors to stop. am I doing something fundamentally wrong, or misunderstanding something? I'm hoping this is fairly simple to some people, as i'm just learning. the point of this program is to calculate taxes and dealership fees on cars using methods and arrays.
package taxesandfeescar;
import java.util.Scanner;
import java.util.Arrays;
/**
*
* #author K
*/
public class Taxesandfeescar {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many vehicle prices would you like to store?");
int pricesNumber = input.nextInt();
int Prices[] = new int[pricesNumber];
for(int i = 0; i < pricesNumber; i++) {
int imsg = i + 1;
System.out.println("Please enter the price, Without taxes or fees, of car #" + imsg);
Prices[i] = input.nextInt();
}
for(int i = 0; i < pricesNumber; i++) {
int imsg = i + 1;
System.out.println("The final price, after taxes and fees of car #" + imsg + " is " + pricesTaxFees[i]);
Prices[i] = input.nextInt();
int pricesTaxFees[i] = applyTaxesAndFees[i];
}
}
public static double[] applyTaxesAndFees(int Prices, int pricesNumber){
int pricesTaxFees[pricesNumber];
for(int i = 0; i < pricesNumber; i++) {
pricesTaxFees[i] = Prices[i] / 13 * 100 + 1500;
}
return pricesTaxFees[];
}
}
You have several errors in your code. For example: you dont have to read twice the price of the car. You cannot print the message with the final price before calculating the final price. When you have defined like that applyTaxesAndFees(int Prices, int pricesNumber) you cannot call it like thatapplyTaxesAndFees[i], it is totaly wrong. You shoul call this method like applyTaxesAndFees(Price, priceNumber).
Anyway, check the code above and find and learn from your mistakes like we all do. Have fun with java.
This will work for you.
import java.util.Scanner;
import java.util.Arrays;
/**
*
* #author K
*/
public class Taxesandfeescar {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many vehicle prices would you like to store?");
int pricesNumber = input.nextInt();
int Prices[] = new int[pricesNumber];
int pricesTaxFees[] = new int[pricesNumber];
for(int i = 0; i < pricesNumber; i++) {
int imsg = i + 1;
System.out.println("Please enter the price, Without taxes or fees, of car #" + imsg);
Prices[i] = input.nextInt();
}
for(int i = 0; i < pricesNumber; i++) {
int imsg = i + 1;
pricesTaxFees[i] = applyTaxesAndFees(Prices[i]);
System.out.println("The final price, after taxes and fees of car #" + imsg + " is " + pricesTaxFees[i]);
}
}
public static int applyTaxesAndFees(int Price){
int pricesTaxFees = 0;
pricesTaxFees = Price / 13 * 100 + 1500;
return pricesTaxFees;
}
}
Here is something working:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many vehicle prices would you like to store?");
int numberOfVehicles = input.nextInt();
double[] vehiclePrices = new double[numberOfVehicles];
for (int i = 0; i < numberOfVehicles; i++) {
int vehicleNumber = i + 1;
System.out.println("Please enter the price, Without taxes or fees, of car #" + vehicleNumber);
vehiclePrices[i] = input.nextInt();
}
for (int i = 0; i < numberOfVehicles; i++) {
int vehicleNumber = i + 1;
vehiclePrices[i] = applyTaxesAndFees(vehiclePrices[i]);
System.out.println("The final price, after taxes and fees of car #" + vehicleNumber + " is " + vehiclePrices[i]);
}
}
public static double applyTaxesAndFees(double pricesBeforeTaxes) {
double priceAfterTaxes = pricesBeforeTaxes + ((pricesBeforeTaxes * 13) / 100) + 1500;
return priceAfterTaxes;
}
my advice would be to check the changes line by line and see the differences. I'm learning as well, but would recommend you to read more about how methods and arrays works. Also - naming conventions are important.
I want to start by saying that I'm a newby in Java, and it's also my first time asking something on this site. After 3 days trying to figure out how to break this small program in methods, I haven't been able to do so. could anyone help me with it ?
I've been reading and it looks like I'm violating the single responsibility principle. Any opinions would be more than welcome.
public class RateSystem {
double employeeSalary;
public int salaryRate(String employeePosition) {
if (employeePosition.equalsIgnoreCase("1")) {
return 40;
} else if (employeePosition.equalsIgnoreCase("2")) {
return 30;
} else
employeePosition.equalsIgnoreCase("3");
return 50;
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Employee position please...");
System.out.println("Press 1 for IT " + "\n" + "Press 2 for Tech" +
"\n" + "Press 3 for engineer");
String ePosition = input.nextLine();
RateSystem raul = new RateSystem();
int getPay = raul.salaryRate(ePosition);
System.out.println("How many hours did he work for the week?...");
int weekHours = input.nextInt();
int totalPay = 0;
if (weekHours <= 40) {
totalPay = getPay * weekHours;
System.out.println("Employee salary is " + totalPay);
} else {
int overTimeHours = weekHours - 40;
int extra$$PerOverTime = overTimeHours * getPay +(overTimeHours * getPay/2);
totalPay = getPay * (weekHours - overTimeHours);
System.out.println("The employee accumulated 40 hours equivalent to $"+
totalPay + " plus $" + extra$$PerOverTime + " overtime hours, a total of $"+(extra$$PerOverTime + totalPay));
}
}
}
If we are looking at main(), It does multiple tasks:
Receive user input
Calculate total pay and possible other finance information
Print the results
How's that for starters
I see followings could be added.
1) Salaries are created for Employees so why don't you create and Employee class and encapsulate details inside it like "employeePosition". So you can add more things later and having setters inside it you will get the chance of changing setter logics for employees.
2) You can create a Calculator class and create methods accepting single Employee or a List of Employees and calculate their Salary Rates.
3) You also can add a Printing related class. So you can produce different printing for single or List of Employees or may be like a tabular format.
I have identified following methods in your code.
1) showMainMenu --> responsible to show menu to the user
2) readMenuSelection --> here you will read whatever user has selected in the main menu. It should be read in int value rather than string.
3) For each Selection from menu there will be separate methods such as payForIT(), payForTech() and payForEngineer()
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Employee position please...");
System.out.println("Press 1 for IT " + "\n" + "Press 2 for Tech" + "\n" + "Press 3 for engineer");
String position = input.nextLine();
RateSystem rateSystem = new RateSystem();
rateSystem.setEmployeePosition(position);
System.out.println("How many hours did he work for the week?...");
int weekHours = input.nextInt();
rateSystem.setWeekHours(weekHours);
rateSystem.calculateSalary();
int totalPay = rateSystem.getTotalPay();
int overTime = rateSystem.getOvertime();
if (overTime > 0) {
System.out.println("The employee accumulated 40 hours equivalent to $" + totalPay + " plus $" + overTime
+ " overtime hours, a total of $" + (overTime + totalPay));
} else {
System.out.println("Employee salary is " + totalPay);
}
}
}
public class RateSystem {
private final int STANDARD_WORK = 40;
private double employeeSalary;
private int weekHours;
private Position employeePosition;
private int totalPay = 0;
private int overTime = 0;
public void setEmployeePosition(String position) {
employeePosition = Position.fromString(position);
}
public void setWeekHours(int weekHours) {
this.weekHours = weekHours;
}
public int getTotalPay() {
return totalPay;
}
public int getOvertime() {
return overTime;
}
public void calculateSalary() {
int salaryRate = employeePosition.getRate();
int workhours = (weekHours > STANDARD_WORK) ? STANDARD_WORK : weekHours;
int overTimeHours = (weekHours > STANDARD_WORK) ? (weekHours - STANDARD_WORK) : 0;
totalPay = workhours * weekHours;
overTime = (overTimeHours * salaryRate) + (overTimeHours * salaryRate / 2);
}
}
public enum Position {
IT(40), Tech(30), Engineer(50);
private int rate = 0;
Position(int r) {
rate = r;
}
public int getRate() {
return rate;
}
public static Position fromString(String position) {
switch (position) {
case "1":
return IT;
case "2":
return Tech;
case "3":
return Engineer;
}
return null;
}
}
To follow single responsibility principle you have to create method for each common task in your program. That helps do not repeat code and helps to modify code in one place.
I have created separate methods for building string and for printing string as you use it frequently in your code:
package com.stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
println("Employee position please...");
println(buildString("Press 1 for IT ", "\n", "Press 2 for Tech", "\n", "Press 3 for engineer"));
String ePosition = input.nextLine();
RateSystem raul = new RateSystem();
int getPay = raul.salaryRate(ePosition);
println("How many hours did he work for the week?...");
int weekHours = input.nextInt();
int totalPay = 0;
if (weekHours <= 40) {
totalPay = getPay * weekHours;
println(buildString("Employee salary is ", String.valueOf(totalPay)));
} else {
int overTimeHours = weekHours - 40;
int extra$$PerOverTime = overTimeHours * getPay + (overTimeHours * getPay / 2);
totalPay = getPay * (weekHours - overTimeHours);
println(buildString("The employee accumulated 40 hours equivalent to $", String.valueOf(totalPay),
" plus $", String.valueOf(extra$$PerOverTime), " overtime hours, a total of $",
String.valueOf((extra$$PerOverTime + totalPay))));
}
}
private static String buildString(String... strings) {
StringBuilder builder = new StringBuilder();
for (String string : strings) {
builder.append(string);
}
return builder.toString();
}
private static void println(String s) {
System.out.println(s);
}
}
And class RateSystem:
package com.stackoverflow.main;
public class RateSystem {
double employeeSalary;
public int salaryRate(String employeePosition) {
if (equalsIgnoreCase(employeePosition, "1")) {
return 40;
} else if (equalsIgnoreCase(employeePosition, "2")) {
return 30;
} else if (equalsIgnoreCase(employeePosition, "3"))
return 50;
return 0;
}
private boolean equalsIgnoreCase(String arg1, String arg2) {
return arg1.equalsIgnoreCase(arg2);
}
}
The below code is not calculating the best way to distribute change in a Java 'cash register'. How do I fix it?
public void generateUSDChange(){
change = payment-purchase;
quarters = (int) (change/.25);
change -= (quarters * .25);
dimes = (int) (change/.1);
change -= (dimes * .1);
nickels = (int) (change/.05);
change -= (nickels * .05);
pennies = (int) (change/.01);
changeamount = quarters*.25 + dimes*.1 + nickels*.05 + pennies*.01;
if(changeamount != (payment-purchase)){
pennies++;
if(pennies>=5){
nickels++;
pennies-=5;
}
if(nickels>=2){
dimes++;
nickels-=2;
}
if(((dimes*.1) + (nickels*.05)) >= .25){
quarters++;
dimes-=2;
nickels--;
}
}
}
As others also suggested double and floats are not good for currency. You can use BigDecimal. Here's the working code:
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;
public enum CurrencyDenomination {
HUNDRED(BigDecimal.valueOf(100)), FIFTY(BigDecimal.valueOf(50)), TWENTY(BigDecimal.valueOf(20)),
TEN(BigDecimal.valueOf(10)), FIVE(BigDecimal.valueOf(5)), ONE(BigDecimal.valueOf(1)),
QUARTER(BigDecimal.valueOf(.25)), DIME(BigDecimal.valueOf(.10)),
NICLE(BigDecimal.valueOf(.05)), PENNIES(BigDecimal.valueOf(.01));
private BigDecimal value;
CurrencyDenomination(BigDecimal value) {
this.value = value;
}
public static Map<CurrencyDenomination, Integer> calculate(BigDecimal balance) {
Map<CurrencyDenomination, Integer> balanceCurrency = new LinkedHashMap<CurrencyDenomination, Integer>();
BigDecimal leftOver = balance;
System.out.println("Given amount : "+balance);
for (CurrencyDenomination currencyDenomination : CurrencyDenomination
.values()) {
int count = leftOver.divide(currencyDenomination.value).intValue();
if (leftOver != BigDecimal.ZERO) {
if (balanceCurrency.containsKey(currencyDenomination)) {
int existingCount = balanceCurrency
.get(currencyDenomination);
existingCount = existingCount + count;
balanceCurrency.put(currencyDenomination, existingCount);
} else {
balanceCurrency.put(currencyDenomination, count);
}
}
leftOver = leftOver.remainder(currencyDenomination.value);
if (leftOver.equals(BigDecimal.ZERO)) {
break;
}
}
return balanceCurrency;
}
public static void main(String[] args) {
System.out.println("BalanceCurrency : "+calculate(BigDecimal.valueOf(49.52)));
}
}
Output:
Given amount : 49.52
BalanceCurrency : {HUNDRED=0, FIFTY=0, TWENTY=2, TEN=0, FIVE=1, ONE=4, QUARTER=2, DIME=0, NICLE=0, PENNIES=2}
I agree with the above answer and comment about using BigDecimal. Another way to handle it would be to use integer values that represent cents, assuming you are using USD currency. You could try something like this. (The currency amounts are just examples for easy testing)
public void generateUSDChange(){
int payment = 500; //$5.00
int purchase = 268; //$2.68
int change = payment - purchase;
int quarters = change / 25;
change = change % 25;
int dimes = change / 10;
change = change % 10;
int nickles = change / 5;
int pennies = change % 5;
System.out.println("Your change is " + quarters + " quarters " + dimes + " dimes " + nickles + " nickles, and "+ pennies + " pennies.");
int change = pennies * 1 + nickles * 5 + dimes * 10 + quarters * 25;
System.out.printf("Your change totals to $%d.%02d", change/100, change%100);}
I'm learning java. I suspect my compute_Hailstone_Sequence method terminates upon hitting a return statement. With the two inputs of begin_num = 7 and steps = 10 my ideal output should represent 7 22 11 34 17 52 26 13 40 20 I also suspect I am not yet incrementing x as my code DOES produces the first two values 7 22 ..I am not sure it can yet produce a cumulative algorithm. I am aware of answers using data structures but I am trying to code this without using lists or arrays or any other data structure. This is not homework.
import java.util.Scanner;
/**
* Created on 9/5/15.
* Following Reges, Stuart, and Martin Stepp. Building Java Programs: A Back to Basics Approach. 3rd Edition.
* Chapter 4
*/
public class Ch4 {
public static void main(String[] args) {
hailstone_Sequence();
}
public static void hailstone_Sequence(){
giveIntro();
Scanner user_console = new Scanner(System.in);
System.out.println("Please provide a starting integer: ");
int BEGINVALUE = user_console.nextInt();
// System.out.println("Please provide an ending integer: ");
// int ENDVALUE = user_console.nextInt();
System.out.println("Thank you. How long would you liked the sequence to be?");
int STEPS = user_console.nextInt();
System.out.println("Calculating..");
compute_Hailstone_Sequence(BEGINVALUE, STEPS);
}
public static int compute_Hailstone_Sequence(int begin_num, int steps){
System.out.print(begin_num + " ");
for (int i = 1; i <= steps; i++ ){
int x;
if ((begin_num & 1) == 0 ){
// even
// int x = 0;
x = (begin_num / 2);
System.out.print(x + " ");
// return x;
}
else {
// int x = 0;
x = (3 * begin_num + 1);
System.out.print(x + " ");
// return x;
}
return x;
}
return begin_num;
}
}
Try this, I do not know if that's what you are looking for, me are based on your output.
public static void hailstone_Sequence(){
Scanner user_console = new Scanner(System.in);
System.out.println("Please provide a starting integer: ");
int BEGINVALUE = user_console.nextInt();
System.out.println("Thank you. How long would you liked the sequence to be?");
int STEPS = user_console.nextInt();
System.out.println("Calculating..");
compute_Hailstone_Sequence(BEGINVALUE, STEPS);
}
public static void compute_Hailstone_Sequence(int begin_num, int steps){
System.out.print(begin_num + " ");
for (int i = 1; i < steps; i++ ){
if (begin_num%2 == 0 ){
begin_num = (begin_num / 2);
System.out.print(begin_num + " ");
}
else {
begin_num = (3 * begin_num) + 1;
System.out.print(begin_num + " ");
}
}
}
Output is:
Please provide a starting integer:
7
Thank you. How long would you liked the sequence to be?
10
Calculating..
7 22 11 34 17 52 26 13 40 20
import java.util.Scanner;
/**
* Created by on 9/5/15.
* Following Reges, Stuart, and Martin Stepp. Building Java Programs: A Back to Basics Approach. 3rd Edition.
* Chapter 4
*/
public class Ch4 {
public static void main(String[] args) {
hailstone_Sequence();
}
public static void hailstone_Sequence(){
giveIntro();
Scanner user_console = new Scanner(System.in);
System.out.println("Please provide a starting integer: ");
int BEGINVALUE = user_console.nextInt();
// System.out.println("Please provide an ending integer: ");
// int ENDVALUE = user_console.nextInt();
System.out.println("Thank you. How long would you liked the sequence to be?");
int STEPS = user_console.nextInt();
System.out.println("Calculating..");
compute_Hailstone_Sequence(BEGINVALUE, STEPS);
}
public static int compute_Hailstone_Sequence(int begin_num, int steps) {
// expected output = 7 22 11 34 17 52 26 13 40 20 10
System.out.print(begin_num + " ");
int x = 0;
for (int i = 1; i <= steps; i++) {
if ((begin_num & 1) == 0) {
// even
// int x = 0;
x = (begin_num / 2);
System.out.print(x + " ");
// return x;
begin_num = x;
} else {
// int x = 0;
x = (3 * begin_num + 1);
System.out.print(x + " ");
// return x;
begin_num = x;
}
}
return x;
}
public static void giveIntro(){
System.out.println("In mathematics, there is an open problem that involves\n " +
"what are known as hailstone sequences.\n" +
"These sequences of numbers often rise and\n " +
"fall in unpredictable pattern, which is somewhat\n" +
" analogous to the process that forms hailstones.\n");
System.out.println("This method outputs hailstone sequences:");
}
}