Creating a Menu of Items via ArrayLists [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
so what I'm trying to do is create a menu of food items with ArrayLists. My task is to complete the following definition of the static method profits that inputs an ArrayList items of MenuItems and returns an array of doubles. Each entry in the output is the difference between the price and the cost of the corresponding element of items. I have to process the result of each calculation involving money using the static method roundMoney.
public class MenuItem
{
private String myName;
private double myPrice,
myCost;
private int myCode;
private boolean myAvailability;
public MenuItem( String name, double price, double cost, int code, boolean available )
{
myName = name;
myPrice = price;
myCost = cost;
myCode = code;
myAvailability = available;
}
public String getName() { return myName; }
public double getPrice() { return myPrice; }
public double getCost() { return myCost; }
public int getCode() { return myCode; }
public boolean available() { return myAvailability; }
public String menuString()
{
return getName() + " ($" + getPrice() + ")";
}
public static double roundMoney( double amount )
{
return (int)(100 * amount + 0.5) / 100.0;
}
public static String printAmount( double d )
{
String s = "" + d;
int k = s.indexOf( "." );
if ( k < 0 )
return s + ".00";
if ( k + 1 == s.length() )
return s + "00";
if ( k + 2 == s.length() )
return s + "0";
else
return s;
}
}
//***********************************************************************
public static double[] Profits(ArrayList<MenuItem> items)
{
double[] profits = new double[items.size()];
for (int i = 0; i < profits.length; i++)
{
profits[i] = roundMoney (items.get(i).getPrice() - items.get(i).getCost());
}
return profits;
}
//***********************************************************************
public static void main( String[] args )
{
ArrayList<MenuItem> items1 = new ArrayList<MenuItem>();
items1.add( new MenuItem("Stir Fry",5.43,0.45,1,true) );
items1.add( new MenuItem("Nachos",3.49,0.15,0,false) );
items1.add( new MenuItem("Mud Pie",6.50,1.25,2,true) );
items1.add( new MenuItem("Jerk Chicken",8.99,3.20,1,false) );
double[] t = profits( items1 );
for ( double d : t )
System.out.print( printAmount( d ) + " " );
}
My expected result is: 4.98 3.34 5.25 5.79, but I keep receiving the error: TC1.java:30: error: cannot find symbol
double[] t = profits( items1 );
Could somebody please help me figure out what's wrong? Thank you!

You define your function profits with a capital "P."
public static double[] Profits(ArrayList<MenuItem> items)
Change the line with the error to match the name of the function:
double[] t = Profits( items1 );

There is a sytanx issue for the MenuItem.java
Try running the below program.
package com.stackoverflow;
import java.util.ArrayList;
public class MenuItem
{
private String myName;
private double myPrice,
myCost;
private int myCode;
private boolean myAvailability;
public MenuItem( String name, double price, double cost, int code, boolean available )
{
myName = name;
myPrice = price;
myCost = cost;
myCode = code;
myAvailability = available;
}
public String getName() { return myName; }
public double getPrice() { return myPrice; }
public double getCost() { return myCost; }
public int getCode() { return myCode; }
public boolean available() { return myAvailability; }
public String menuString()
{
return getName() + " ($" + getPrice() + ")";
}
public static double roundMoney( double amount )
{
return (int)(100 * amount + 0.5) / 100.0;
}
public static String printAmount( double d )
{
String s = "" + d;
int k = s.indexOf( "." );
if ( k < 0 )
return s + ".00";
if ( k + 1 == s.length() )
return s + "00";
if ( k + 2 == s.length() )
return s + "0";
else
return s;
}
//***********************************************************************
public static double[] profits(ArrayList<MenuItem> items)
{
double[] profits = new double[items.size()];
for (int i = 0; i < profits.length; i++)
{
profits[i] = roundMoney (items.get(i).getPrice() - items.get(i).getCost());
}
return profits;
}
//***********************************************************************
public static void main( String[] args )
{
ArrayList<MenuItem> items1 = new ArrayList<MenuItem>();
items1.add( new MenuItem("Stir Fry",5.43,0.45,1,true) );
items1.add( new MenuItem("Nachos",3.49,0.15,0,false) );
items1.add( new MenuItem("Mud Pie",6.50,1.25,2,true) );
items1.add( new MenuItem("Jerk Chicken",8.99,3.20,1,false) );
double[] t = profits( items1 );
for ( double d : t )
System.out.print( printAmount( d ) + " " );
}
}

Related

How to calculate only integer types in array?

import java.util.*;
class Distance {
private String name;
private int dist;
public Distance(String name, int dist) {
this.name = name;
this.dist = dist;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDist() {
return dist;
}
public void setDist(int dist) {
this.dist = dist;
}
public String toString() {
return "Distance [name=" + name + ", school street=" + dist + "]";
}
}
class DistanceComp {
public static Distance longdistance(Distance[] dim) {
Distance max = dim[0];
for (int i = 1; i < dim.length; i++) {
if (max.getDist() < dim[i].getDist())
max = dim[i];
}
return max;
}
public static Distance shortdistance(Distance[] dim) {
Distance min = dim[0];
for (int i = 1; i < dim.length; i++) {
if (min.getDist() > dim[i].getDist())
min = dim[i];
}
return min;
}
}
public class week03_01 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Distance[] dist = new Distance[3];
System.out.print(">> how many students? : ");
int num = in.nextInt();
for (int i = 0; i < num; i++) {
System.out.print(">> name and distance : ");
dist[i] = new Distance(in.next(), in.nextInt());
}
System.out.println("\na student with the longest commute to school : " + DistanceComp.longdistance(dist));
System.out.println("a student with the shortest commute to school : " + DistanceComp.shortdistance(dist));
System.out.println("school distance difference is " + );
}
}
I also want to print the "shool distance differecnce".
but it doesn't calculate. i think it has String types.
I think calculate only integer types in an array, but i don't know the code.
Or is s there any other way? Ask for advice.
In your DistanceComp class, create a method to subtract two Distances similar like you did for longdistance and shortdistance:
public static int subtractDistance(Distance dist1, Distance dist2) {
int difference = Math.abs(dist1.getDist() - dist2.getDist());
return difference;
}
Then, use that in your System.out:
System.out.println("school distance difference is " + DistanceComp.subtractDistance(DistanceComp.longdistance(dist), DistanceComp.shortdistance(dist)));
Some notes fyi:
Your code currently only works with 3 students.
Instead of using long names, assign them to a shorter-named variable. This helps with code readability.

Trying to retrieve index from Array using loop

I made a program which stores movie names, hour and time of showing.
I saved the details inputted to arrays and then saved the arrays by getter and setter methods as a record.
In my final method i attempt to use a for loop to print out the details stored in the records but constantly get errors.
Any help to where the issue is would be greatly appreciated.
//Demonstrates usage of loops/adt/gettersetters
import java.util.Scanner;
class movies {
public static void main(String[] p) {
Movie m = new Movie();
int[] screenn = new int[4];
int[] namee = new int[4];
int[] hourr = new int[4];
int[] minn = new int[4];
for (int i = 0; i < 4; i++) {
screenn[i] = i + 1;
String moviename = input("Film for screen " + (i + 1));
namee[i] = moviename;
int moviehour = inputint("what hour does it start?");
hourr[i] = moviehour;
int moviemin = inputint("what min does it start?");
minn[i] = moviemin;
}
sethour(m, namee);
setmin(m, minn);
setscreen(m, screen);
setname(m, namee);
showtime(m);
System.exit(0);
}
//Getter Method
public static String[] getname(Movie m) {
return m.name;
}
public static int[] getscreen(Movie m) {
return m.screen;
}
public static int[] gethour(Movie m) {
return m.hour;
}
public static int[] getmin(Movie m) {
return m.min;
}
//Setter Method
public static Movie sethour(Movie m, int[] hour) {
m.hour = hour;
return m;
}
public static Movie setmin(Movie m, int[] min) {
m.min = min;
return m;
}
public static Movie setname(Movie m, String[] name) {
m.name = name;
return m;
}
public static Movie setscreen(Movie m, int[] screen) {
m.screen = screen;
return m;
}
public static String input(String message) {
Scanner scanner = new Scanner(System.in);
print(message);
String answer = scanner.nextLine();
return answer;
}
public static String print(String message) {
System.out.println(message);
return message;
}
public static int inputint(String message) {
int number = Integer.parseInt(input(message));
return number;
}
public static void showtime(movie m) {
print("Cineworld Movies For Tonight");
for (int i = 0; i < 4; i++) {
print("");
print(m.screen[i]);
print(m.movie[i]);
print(m.hour[i]);
print(m.min[i]);
}
}
}
class Movie {
String[] name = new String[4];
int[] hour = new int[4];
int[] min = new int[4];
int[] screen = new int[4];
}
You are getting your assignment wrong. According to OOP The Movie class should store Movie's properties (name, hour, mins, etc) and then on your MainProgram you should store an array of movies. How you create and the usage of these objects is not concern of the class it self. Having said that i re-implemented your mainProgram to:
Ask for each (4) movie attributes.
Create the movie.
add it to a list of movies.
for each movie (4) print its properties.
MovieClass:
public class Movie
{
String name;
int hour , min , screen;
public Movie ( )
{
super ( );
}
public Movie ( String name , int hour , int min , int screen )
{
super ( );
this.name = name;
this.hour = hour;
this.min = min;
this.screen = screen;
}
public String getName ( )
{
return name;
}
public void setName ( String name )
{
this.name = name;
}
public int getHour ( )
{
return hour;
}
public void setHour ( int hour )
{
this.hour = hour;
}
public int getMin ( )
{
return min;
}
public void setMin ( int min )
{
this.min = min;
}
public int getScreen ( )
{
return screen;
}
public void setScreen ( int screen )
{
this.screen = screen;
}
#Override
public String toString ( )
{
return "Movie [name=" + name + ", hour=" + hour + ", min=" + min + ", screen=" + screen
+ "]";
}
}
MainProgram:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MainProgram
{
public static void main ( String [ ] args )
{
List < Movie > movieList = new ArrayList < Movie > ( );
for(int i = 1; i <= 4; i++ )
{
int screen = i;
String name = inputString ( "Film for screen "+(i));
int hour = inputInt ("what hour does it start?");
int min = inputInt ("what min does it start?");
Movie movie = new Movie ( name , hour , min , screen );
movieList.add ( movie );
}
print("Cineworld Movies For Tonight");
for( Movie movie : movieList)
{
print ( "" );
print ( Integer.toString ( movie.getScreen ( ) ));
print (movie.getName ( ));
print (Integer.toString ( movie.getHour ( ) ));
print ( Integer.toString ( movie.getMin ( ) ));
}
}
public static String inputString ( String message )
{
Scanner scanner = new Scanner ( System.in );
print ( message );
String answer = scanner.nextLine ( );
return answer;
}
public static String print ( String message )
{
System.out.println ( message );
return message;
}
public static int inputInt ( String message )
{
int number = Integer.parseInt ( inputString ( message ) );
return number;
}
}
Note: as you can see i re-used some of your static methods but if you need something else you have to implement it by yourself.
I/O Example:
Film for screen 1
The Shawshank Redemption
what hour does it start?
19
what min does it start?
30
Film for screen 2
The Godfather
what hour does it start?
20
what min does it start?
15
Film for screen 3
The Godfather: Part II
what hour does it start?
20
what min does it start?
30
Film for screen 4
The Dark Knight
what hour does it start?
21
what min does it start?
15
Cineworld Movies For Tonight
1
The Shawshank Redemption
19
30
2
The Godfather
20
15
3
The Godfather: Part II
20
30
4
The Dark Knight
21
15
Hope it helps.

Unidentified runtime error--Could not launch/Console

I am experiencing a strange error after I compile and run my program. I believe that these are called run time errors? Is that correct? The program compiles perfectly, all of the classes included. When I open the compiled program, I am prompted (correctly) to enter all information and after that when the program is supposed to print out the final output I receive a pop up error message ( with a yellow exclamation point on the java coffee cup) that says " The Java Class file 'Employee10.java' could not be launched. Check console for possible error messages. " Does anyone know why I am getting this message if the rest of the program runs correctly? Is my print statement not correct? Below I have added all the classes just incase the error isn't necessarily in Employee10.java. If anyone can help at all with this I would be very grateful. I am new to Java programing and could really use the help and guidance. Thank you very much all.
Here is Employee10
public class Employee10
{
public static void main ( String[] args )
{
System.out.println("Begin Program");
Employee e1 = new Employee();
Employee[] arr = new Employee[2];
int j = 0;
for ( int i=0; i < 3; i++)
{
arr[0] = e1;
String nameF = Input.getString("Please enter a First Name");
String nameL = Input.getString("Please enter a Last Name");
int Number = Input.getInt("Please enter an Employee Number");
String Street = Input.getString("Please enter a Street address");
String City = Input.getString("Please enter a City");
String State = Input.getString("Please enter a State");
double Zip = Input.getDouble("Please enter a Zip Code");
int Month = Input.getInt("Please enter a Month in numbers");
int Day = Input.getInt("Please enter a Day");
int Year = Input.getInt("Please enter a Year");
e1.setNumber(Number);
e1.setName( new Name(nameF, nameL));
e1.setAddress(new Address(Street, City, State, Zip));
e1.setHireDate(new Date(Month, Day, Year));
System.out.println(e1.getEmployeeString());
arr[i] = e1;
}
for ( j=0; j < arr.length; j++ )
{
System.out.println( arr[j].getEmployeeString() );
}
}
}
Here is Employee
public class Employee
{
private int Number;
Name name;
Address address;
Date HireDate;
public void setNumber ( int N )
{
Number = N;
}
public void setName ( Name n )
{
name = n;
}
public void setAddress ( Address a )
{
address = a;
}
public void setHireDate ( Date h )
{
HireDate = h;
}
public String getEmployeeString()
{
return name.getNameString() + Number + address + HireDate;
}
}
Here is Date
public class Date
{
private int month;
private int day;
private int year;
public Date() { month = 0; day = 0; year = 0; }
public void setDate( int m, int d, int y )
{
month = m; day = d; year = y;
}
public String getDateString()
{
return month + "/" + day + "/" + year;
}
public Date( int m, int d, int y )
{
month = m;
day = d;
year = y;
}
}
Here is Name
public class Name
{
private String NameF;
private String NameL;
public void setNameF ( String F )
{
NameF = F;
}
public void setNameL ( String L )
{
NameL = L;
}
public String getNameString ()
{
return NameF + NameL;
}
public Name ( String F, String L )
{
NameF = F;
NameL = L;
}
public Name ()
{
NameF = "John";
NameL = "Doe";
}
}
Here is Address
public class Address
{
private String Street;
private String City;
private String State;
private double Zip;
public void setStreet ( String s )
{
Street = s;
}
public void setCity ( String c )
{
City = c;
}
public void setState ( String T )
{
State = T;
}
public void setZip ( double z )
{
Zip = z;
}
public String GetAddressString ()
{
return Street + City + State + Zip;
}
public Address ( String s, String c, String T, double z )
{
Street = s;
City = c;
State = T;
Zip = z;
}
public Address ()
{
Street = "No street";
City = " No City";
State = "No state";
Zip = 00000;
}
}
Here is Input
import javax.swing.*;
public class Input
{
public static byte getByte( String s )
{
String input = JOptionPane.showInputDialog( s );
return Byte.parseByte( input );
}
public static short getShort( String s )
{
String input = JOptionPane.showInputDialog( s );
return Short.parseShort( input );
}
public static int getInt( String s )
{
String input = JOptionPane.showInputDialog( s );
return Integer.parseInt( input );
}
public static long getLong( String s )
{
String input = JOptionPane.showInputDialog( s );
return Long.parseLong( input );
}
public static float getFloat( String s )
{
String input = JOptionPane.showInputDialog( s );
return Float.parseFloat( input );
}
public static double getDouble( String s )
{
String input = JOptionPane.showInputDialog( s );
return Double.parseDouble( input );
}
public static boolean getBoolean( String s )
{
String input = JOptionPane.showInputDialog( s );
return Boolean.parseBoolean( input );
}
public static char getChar( String s )
{
String input = JOptionPane.showInputDialog( s );
return input.charAt(0);
}
public static String getString( String s )
{
String input = JOptionPane.showInputDialog( s );
return input;
}
}
In Employee class file can you replace
public String getEmployeeString()
{
return name.getNameString() + Number + address + HireDate;
}
with
public String getEmployeeString()
{
return name.getNameString() + Number + address.GetAddressString() + HireDate.getDateString();
}

Converting the same String value into an Object

I have an object share:
Share tea = new Share("TEA", "Common", 0, 100);
ArrayList<Share> shares = new ArrayList<Share>();
shares.add(tea);
What I'd like to do is, reading parameters from the keybord, convert directly the "tea" string into a share tea object :
Trade trade = new Trade( tea, Boolean.parseBoolean(buyOrSell), Integer.parseInt(quantity), Double.parseDouble(tradePrice));
What should I put instead of tea because my constructor is waiting a Share and not a String. The user is entering a string and I don't need ton create a new instance, I have to use the Share object "tea" that already exists.
The Share.java class :
public class Share {
private String shareSymbol = "";
private String type = "Common";
private double lastDividend = 0;
private double fixedDividend = 0;
private int parValue = 0;
// Calucul values
public String getShareSymbol() {
return shareSymbol;
}
public String getType() {
return type;
}
public double getLastDividend() {
return lastDividend;
}
public double getFixedDividend() {
return fixedDividend;
}
public int getParValue() {
return parValue;
}
// Constructor without Fixed Dividend
public Share(String shareSymbol, String type, int lastDividend, int parValue) {
this.shareSymbol = shareSymbol;
this.type = type;
this.lastDividend = lastDividend;
this.parValue = parValue;
}
// Constructor with Fixed Dividend
public Share(String shareSymbol, String type, int lastDividend,
int fixedDividend, int parValue) {
this(shareSymbol, type, lastDividend, parValue);
this.fixedDividend = fixedDividend / 100.0;
}
public String toString(){
String result="";
result += shareSymbol + " "+type + " " + lastDividend + " " + fixedDividend + " " + parValue + "\n";
return result;
}
}
The Trade.java class :
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
// The class trade allows the stock, the quantity and the price to be intialised
public class Trade {
Share share;
private int quantity;
double price;
private double dividendYield;
private double pERatio;
private boolean buyOrSell;
private Date tradeDate;
public Trade(Share share, boolean buyOrSell, int quantity, double price) {
this.share = share;
this.buyOrSell = buyOrSell;
this.quantity = quantity;
this.price = price;
tradeDate = Calendar.getInstance().getTime();
}
public String toString() {
String result = "";
result += "stock symbol : " + share.getShareSymbol() + " \n";
result += "Buy or Sell : " + buyOrSell + " \n";
result += "quantity :" + quantity + " \n";
result += "price : " + price + " \n";
result += "Dividend Yield : " + dividendYield + " \n";
result += "P/E Ratio : " + pERatio + " \n";
result += "tradeDate : " + tradeDate + " \n\n";
return result;
}
public Share getShare() {
return share;
}
public int getQuantity() {
return quantity;
}
public double getPrice() {
return price;
}
public double getDividendYield() {
return dividendYield;
}
public double getpERatio() {
return pERatio;
}
public Date getTradeDate() {
return tradeDate;
}
public double calcDividendYield() {
if ("Common".equalsIgnoreCase(share.getType())) {
dividendYield = share.getLastDividend() / price;
} else if ("Preferred".equalsIgnoreCase(share.getType())) {
dividendYield = share.getFixedDividend() * share.getParValue()
/ price;
}
return dividendYield;
}
public double calcPERatio() {
if (dividendYield > 0)
pERatio = price / dividendYield;
return pERatio;
}
}
Your constructor is waiting a share. So give it:
/* Read parameters from keyboard, stock in s1, s2, i1 and i2 variables */
Trade trade = new Trade( new Share(s1,s2,i1,i2), Boolean.parseBoolean(buyOrSell), Integer.parseInt(quantity), Double.parseDouble(tradePrice));
Otherwise you can implement a method (in Share class) that do it for you
public static Share stringToShare(String s1, String s2, int t1, int t2){
return new Share(s1, s2, t1, t2);
}
And then:
Trade trade = new Trade( Share.stringToShare(...), Integer.parseInt(quantity), Double.parseDouble(tradePrice));
EDIT: better use real variable names that means something, not s1, s2, etc.
I've got around of this, by creating a new constructor :
Trade trade = new Trade(shares, stockSymbol, Boolean.parseBoolean(buyOrSell),
Integer.parseInt(quantity), Double.parseDouble(tradePrice));
This is then the new constructor :
public Trade(ArrayList<Share> shares, String stockSymbol,
boolean buyOrSell, int quantity, double price) {
Iterator<Share> iter = shares.iterator();
int index = -1;
while (iter.hasNext()) {
Share share = iter.next();
index++;
if (stockSymbol.equalsIgnoreCase((share.getShareSymbol()))) {
this.share = shares.get(index);
this.buyOrSell = buyOrSell;
this.quantity = quantity;
this.price = price;
tradeDate = Calendar.getInstance().getTime();
break;
}
}
}
It's a bit complacated, because I had also to create a new method to get the Share for the given String(having the same name, for instance). But that does What i needed.
It would be cleaner though to make it with Java Reflection, without having to create a new constructor. So if any one have an idea with a code more clever, I would be happy!

Cannot find Symbol MenuItem

I'm writing a code where I have an ArrayList input and from that ArrayList I have to get two numbers from that and subtract them. When I'm doing this I get a Cannot find Symbol error. Why am I getting this error?
public static double[] profits( ArrayList<MenuItem> items )
{
double[] lol = new double[items.size()];
for ( MenuItem z : items )
{
for ( int i = 0; i < lol.length ; i++ )
{
lol[i] = roundMoney(getPrice() - getCost());
}
return lol;
}
}
this is the main class:
ArrayList<MenuItem> items = new ArrayList<MenuItem>();
items.add( new MenuItem( "Alliteration Armadillo", 20.25, 3.15, 1, true ) );
items.add( new MenuItem( "Consonance Chameleon", 5.45, 0.75, 0, false ) );
items.add( new MenuItem( "Assonance Bass", 1.95, 0.50, 1, false ) );
double[] t = profits( items );
for ( double d : t )
System.out.print( printAmount( d ) + " " );
What my output is supposed to be is a array of doubles that should output {17.10 4.70 1.45}
The error says:
TC1.java:17: cannot find symbol
symbol : method getPrice()
If this isn't enough information then here is the whole class:
public class MenuItem
{
private String myName;
private double myPrice,
myCost;
private int myCode;
private boolean myAvailability;
public MenuItem( String name, double price, double cost, int code, boolean available )
{
myName = name;
myPrice = price;
myCost = cost;
myCode = code;
myAvailability = available;
}
public String getName() { return myName; }
public double getPrice() { return myPrice; }
public double getCost() { return myCost; }
public int getCode() { return myCode; }
public boolean available() { return myAvailability; }
// Create your method here
public String menuString()
{
return getName() + " ($" + getPrice() + ")";
}
public static double roundMoney( double amount )
{
return (int)(100 * amount + 0.5) / 100.0;
}
public static String printAmount( double d )
{
String s = "" + d;
int k = s.indexOf( "." );
if ( k < 0 )
return s + ".00";
if ( k + 1 == s.length() )
return s + "00";
if ( k + 2 == s.length() )
return s + "0";
else
return s;
}
}
F
In the first code snippet, replace getPrice() and getCost() with z.getPrice() and z.getCost().
Now, to get the output you wanted, fix the first snippet to have:
public static double[] profits(ArrayList<MenuItem> items)
{
double[] lol = new double[items.size()];
int i = 0;
for (MenuItem z : items)
{
lol[i] = roundMoney(z.getPrice() - z.getCost());
i++;
}
return lol;
}
You have forgotten to use the Object Reference Variable z of type MenuItem to access its method getPrice() and getCost()
Use z with dot operator to call the method.
eg:
z.getPrice() and z.getCost()

Categories

Resources