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.");
}
Related
import java.util.Scanner;
public class Prac3_Q2_JasmineLimSmith {
Scanner scan;
String set;
int setA = 0, setB = 0, setC = 0, setD = 0;
void createFile() throws Exception {
File file = new File("orders.txt");
scan = new Scanner(file);
}
void readData() {
setA = scan.nextInt();
setB = scan.nextInt();
setC = scan.nextInt();
setD = scan.nextInt();
if (scan.hasNextLine())
scan.nextLine();
}
void calcOrder() {
double order = ((setA * 9.90) + (setB * 10.90) + (setC * 11.90) + (setD * 12.90));
double totalOrder = (order);
System.out.println("Set A " + setA);
System.out.println("Set B " + setB);
System.out.println("Set C " + setC);
System.out.println("Set D " + setD);
System.out.printf("Total price: %.2f", order);
System.out.println();
}
public static void main(String args[]) throws Exception {
Prac3_Q2_JasmineLimSmith cc = new Prac3_Q2_JasmineLimSmith();
cc.createFile();
for (int cnt = 1; cnt <= 10; cnt++) {
cc.readData();
cc.calcOrder();
}
}
}
This is the sample output
Set A 1
Set B 4
Set C 3
Set D 2
Total price: 115.00
Sorry, Im new to java, This is my code so far.
In total there would be 10 outputs like that one.
how would i take all the total prices and calculate it into 1 grand total at the very end?
Any help would be appreciated, Thank you
Welcome to StackOverflow! Are you allowed to change the return types of any methods, or add new parameters/methods? Since this seems like homework, I'll give you a general idea of two possible similar approaches.
One way to do this would be to return the total price from calcOrder (by changing the void return type to double). You can then declare an double sumOfOrders = 0 variable outside of your loop where you call calcOrder and then keep adding the return value of calcOrder to it. At the end of the loop, you will have the sum of all orders which you can print out.
For example:
double calcOrder() { // note that the return type has been changed from 'void' to 'double'
double order = ((setA * 9.90) + (setB * 10.90) + (setC * 11.90) + (setD * 12.90));
// print statements
return order;
}
Then, in your main function, you can use the return value when calling calcOrder():
double sumOfOrders = 0;
for (int cnt = 1; cnt <= 10; cnt++) {
cc.readData();
// The following can alternatively be written as
// sumOfOrders += cc.calcOrder();
sumOfOrders = sumOfOrders + cc.calcOrder();
}
System.out.printf("Sum of all orders: %.2f", sumOfOrders);
If you are not allowed to change the return types of existing methods, you could:
Make order an instance variable (e.g. private double orderPrice;
Set order to the sum of all prices (e.g. this.orderPrice = ((setA * 9.90) + ...);)
Add a getter for the orderPrice variable (e.g. by adding a double getOrderPrice() { return this.orderPrice; } method in your Prac3_Q2_JasmineLimSmith class)
Sum the orders in the same way as above:
double sumOfOrders = 0;
for (int cnt = 1; cnt <= 10; cnt++) {
cc.readData();
cc.calcOrder();
sumOfOrders = sumOfOrders + cc.getOrderPrice();
}
System.out.printf("Sum of all orders: %.2f", sumOfOrders);
I am a complete beginner in programming and I'm working on a program for my mother that tracks her employee's monetary intake through a "horse race", with each employee having a horse and the program tracking their input to a UI made to look like a racetrack. After the help from my last inquiry, I've greatly simplified my mess of code but I am now faced with a new problem in that, after sorting the values largest to smallest, I have no way of associating the sorted values with the correct horse. I understand this explanation is confusing so I hope my code will do most of the talking for me here.
I honestly have no idea where to start with this. As I said in my last inquiry, I'm a complete beginner and severely lack the terminology or knowledge to find an answer here.
public class HorseRace {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String horse1 = "#5 Gitty-Up";
String horse2 = "#7 Lady Simmons";
String horse3 = "#6 Burning Peanutbutter";
String horse4 = "#10 White Lightning";
String horse5 = "#3 Bella";
String horse6 = "#1 Meg The Stallion";
float h1val;
float h2val;
float h3val;
float h4val;
float h5val;
float h6val;
System.out.println("Input amount for " + horse1 + ":");
h1val = sc.nextFloat();
System.out.println("Input amount for " + horse2 + ":");
h2val = sc.nextFloat();
System.out.println("Input amount for " + horse3 + ":");
h3val = sc.nextFloat();
System.out.println("Input amount for " + horse4 + ":");
h4val = sc.nextFloat();
System.out.println("Input amount for " + horse5 + ":");
h5val = sc.nextFloat();
System.out.println("Input amount for " + horse6 + ":");
h6val = sc.nextFloat();
Float[] values = new Float[]{h1val, h2val, h3val, h4val, h5val, h6val};
Arrays.sort(values, Collections.reverseOrder());
//currently displays horses with the wrong number. Need a way to tie the horse name strings to their respective float elements
System.out.println("The current race progress is :");
System.out.println(horse1 + " with $" + values[0]);
System.out.println(horse2 + " with $" + values[1]);
System.out.println(horse3 + " with $" + values[2]);
System.out.println(horse4 + " with $" + values[3]);
System.out.println(horse5 + " with $" + values[4]);
System.out.println(horse6 + " with $" + values[5]);
}
}
my desired result is printing the correct horse with the correct value. For example, if I put that #5 brought in $11 and #7 brought in $14, the program would print that #7 is in the lead with $14 and #5 is in second place with $11.
Currently, the program always prints #5 as being in the lead with the highest value, #7 being in second with the second highest, etc.
I understand this is because I am hard calling the horse1-horse6 values meaning they don't change, but these are acting more as placeholders while I figure out how to associate the right horse with the right value
This is where you should create a Horse class and store the data as instances of Horse.
class Horse {
private String name;
private float value;
public String getName() { return name; }
public float getValue() { return value; }
public void setName(String name) { this.name = name; }
public void setValue(float value) { this.value = value; }
}
And then in your main method:
Horse[] horses = new Horse[6] {
new Horse(), new Horse(), new Horse(), new Horse(), new Horse(), new Horse()
};
horses[0].setName("#5 Gitty-Up");
horses[1].setName("#7 Lady Simmons");
horses[2].setName("#6 Burning Peanutbutter");
// and so on...
// you should use a for loop here instead of writing similar lines over and over again!
for (int i = 0 ; i < 6 ; i++) {
System.out.println("Input amount for " + horses[i].getName() + ":");
horses[i].setValue(sc.nextFloat());
}
Arrays.sort(horses, Comparator.comparingDouble(Horse::getValue).reversed());
System.out.println("The current race progress is :");
for (int i = 0 ; i < 6 ; i++) {
System.out.println(horses[i].getName() + " with $" + horses[i].getValue());
}
By using a class, you are essentially grouping data that belongs together, together. On the line Arrays.sort(horses, Comparator.comparingDouble(Horse::getValue).reversed());, I am sorting the whole array of horses together, by their values.
If the concepts of classes and objects are new to you, that just means it's time to learn about some new concepts. Classes and objects are very important.
Step 1, create a Horse class. It should have two fields, amount and name. It should implement Comparable because you want to sort it. And looking at your desired output, I would override toString().
class Horse implements Comparable<Horse> {
private String name;
private float amount;
public Horse(String name, float amount) {
this.name = name;
this.amount = amount;
}
#Override
public String toString() {
return String.format("%s with $%.2f", name, amount);
}
#Override
public int compareTo(Horse o) {
return Comparator.comparing((Horse h) -> h.amount)
.thenComparing((Horse h) -> h.name).compare(this, o);
}
}
Step 2, create an array of horseNames and iterate that populating an array of Horses (with amounts). Then sort it, and I would prefer Comparator.reverseOrder() to Collection.reverseOrder() when sorting an array.
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String[] horseNames = { "#5 Gitty-Up", "#7 Lady Simmons",
"#6 Burning Peanutbutter", "#10 White Lightning",
"#3 Bella", "#1 Meg The Stallion" };
Horse[] horses = new Horse[horseNames.length];
for (int i = 0; i < horseNames.length; i++) {
System.out.printf("Input amount for %s:%n", horseNames[i]);
float amt = sc.nextFloat();
horses[i] = new Horse(horseNames[i], amt);
}
Arrays.sort(horses, Comparator.reverseOrder());
System.out.println("The current race progress is :");
for (int i = 0; i < horses.length; i++) {
System.out.println(horses[i]);
}
}
I need to make this into four separate columns
public class Lab7aCelsiustoFahrenheit
{
public static void main(String[] args)
{
//variables
double orig = -40.0;
double cels = orig;
double fahr = cels;
final int MAX_TEMP = -1;
//loop that prints asingle column on celsius to F conversions
while(cels <= MAX_TEMP)
{
System.out.println(cels + "C " + "is " + fahr + "F" + "\t");
cels++;
fahr = (((9.0 * cels) + 160) / 5);
}
}
}
You can make a linebreak after 4 entries, in counting how many items u wrote and then start in the next line.
Also to have each "cell" below the other you should use System.out.printf for writing the entry to format the double-values
If you really want to do this in a single while-loop, a possibilty would be:
int column = 1;
while(cels <= MAX_TEMP) {
fahr = (((9.0 * cels) + 160) / 5);
System.out.printf("%8.2fC is %8.2fF" + "\t", cels, fahr);
cels++;
column++;
if(column > 4) {
column = 1;
System.out.println();
}
}
I think you should also do the calculation before System.out.printf(...)
I'm having trouble trying to find out the running total. Each time I calculate the running total it miscalculates and gives me the incorrect answer. I'm not sure what it is. I cant tell if it has something to do with the method calling I did in main, the if statement in takeOrder or neither.
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class MyCoffeeHouse {
public static void main(String[] args) {
String name = JOptionPane.showInputDialog(null, "What is your name?");
greetCustomer(name);
double totalPrice = takeOrder(name);
calculateFinalPrice(totalPrice);
}
public static void greetCustomer(String name) {
// greet customer
JOptionPane.showMessageDialog(null, "Hello " + name + ", Welcome to A Cup of Java!");
}
public static double takeOrder(String name) { // this method returns
String[] food = {"coffee", "bagel", "tea", "muffin"};
double[] price = {3.99, 1.99, 2.99, 4.99};
double totalprice = 0;
DecimalFormat dec = new DecimalFormat("#.00");
for (int index = 0; index < food.length; index++) {
JOptionPane.showMessageDialog(null, "Our menu offers: " + food[index] + "(s) which is " + "$"
+ price[index]);
}
int numItems =
Integer.parseInt(JOptionPane.showInputDialog(name + ", How many items are "
+ "you interested in purchasing?"));
// running total
for (int index = 0; index < numItems; index++) {
String input =
JOptionPane.showInputDialog(null, "Which items are you interested in purchasing from "
+ "our menu: coffee, bagel, tea, or muffin?");
if (input.equalsIgnoreCase(food[index])) {
totalprice += price[index];
}
}
return totalprice;
}
public static void calculateFinalPrice(double totalPrice) {
double salestax = (totalPrice * 0.07) + totalPrice; // 7% salestax
double finalprice;
DecimalFormat dec = new DecimalFormat("#.00");
int input =
JOptionPane.showConfirmDialog(null, "Would you like to dine in?", "Confirm",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (input == JOptionPane.YES_OPTION) {
finalprice = totalPrice + (salestax * 0.02);
JOptionPane.showMessageDialog(null, "The final price is $" + finalprice);
} else {
DecimalFormat dec = new DecimalFormat("#.00");
JOptionPane.showMessageDialog(null, "The final price is $" + dec.format(salestax));
}
}
}
When you do
double salestax= totalPrice + 0.07; //7% salestax
This means you are adding 7 cents in tax, not 7 percent. To add 7 % you need to multiply the original price by 1.07 or 100% + 7% = 107%
double salestax= totalPrice * 1.07; // add 7% salestax
When you do
finalprice=salestax + 0.02;
You are adding 2 cents. Note: at this point you can add another 2% however adding 7% and another 2% is not the same at adding 9% as 1.07 * 1.02 > 1.09.
Get the chosen food item before you loop to test for the price.
// First get the input
String input=JOptionPane.showInputDialog(null,//
"Which items are you interested in purchasing from "
+ "our menu: coffee, bagel, tea, or muffin?");
for(int index=0;index<numItems;index++) {
// now loop all of the items, and check what was picked.
if(input.equalsIgnoreCase(food[index])) {
totalprice+=price[index];
}
}
I am taking an intro to Java programming and I have the below assignment. I think my code is correct but I get the wrong answer. I need to find the total cost for each car, and "buy" the cheaper one. Suppose that I am traveling 50000 miles:
Fuel cost = $4
Miles driven = 50000
Purchase price for car 1 = $15000
Purchase price for car 2 = $30000
Mpg for car 1 = 10
Mpg for car 2 = 50
gas cost = (Miles driven / Mpg) * Fuel cost
total cost = Purchase price + gas cost
and here is my code:
public class Test
{
public static void main(String[] args)
{
int milesDriven = 50000;
int mpg1 = 10;
int mpg2 = 50;
int pricePerGallon = 4;
int purchasePrice1 = 15000;
int purchasePrice2 = 30000;
int gasCost4Car1 = (milesDriven / mpg1) * pricePerGallon;
int gasCost4Car2 = (milesDriven / mpg2) * pricePerGallon;
int total4Car1 = (purchasePrice1 + gasCost4Car1);
int total4Car2 = (purchasePrice2 + gasCost4Car2);
if(total4Car1 < total4Car2)
{
System.out.println(total4Car1 + gasCost4Car1);
}
else
{
System.out.println(purchasePrice2 + gasCost4Car2);
}
System.out.println(purchasePrice2 + gasCost4Car2); // just to see the output for car 2
}
}
The output I get is 34000
and I believe that for car 1 the output should be 35000
and the output for car 2 should be 34000
I don't understand I am getting the wrong answer.
Note: I can't post pictures (for reputation reasons) nor videos, but I am willing to provide that information if needed.
Thank you.
The problem is on this line:
System.out.println(total4Car1 + gasCost4Car1);
total4Car1 already includes gasCost4Car1.
Here is a demo on ideone printing 34000.
total4car1 is not less than total4car2, so it prints the total for car 2 i.e. purchaseprice2 + gascost4car2, and then it prints it again in System.out.println(purchasePrice2 + gasCost4Car2); // just to see the output for car 2. What should be output?
Cleaned up a little bit, gives correct results:
public static void main(String[] args) {
int milesDriven = 50000;
int mpg1 = 10;
int mpg2 = 50;
int pricePerGallon = 4;
int purchasePrice1 = 15000;
int purchasePrice2 = 30000;
int gasCost4Car1 = milesDriven / mpg1 * pricePerGallon;
int gasCost4Car2 = milesDriven / mpg2 * pricePerGallon;
int total4Car1 = purchasePrice1 + gasCost4Car1;
int total4Car2 = purchasePrice2 + gasCost4Car2;
System.out.println("Total car 1: " + total4Car1);
System.out.println("Total car 2: " + total4Car2);
if (total4Car1 < total4Car2) {
System.out.println("Car 1 is cheaper: " + total4Car1);
} else {
System.out.println("Car 2 is cheaper: " + total4Car2);
}
}