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()
Related
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.
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();
}
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!
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 ) + " " );
}
}
so I have a program that takes a txt file and is read in and uses the class of another java file to set up the array. I am trying use selection sort to sort the values placed into the array but it gives me bad operand types for the line: (if array[j] < array[min]). The text file used is:"Country" "Total CO2 2005 (million tonnes)" "Road CO2 (million tonnes)" "Road CO2 per person (tonnes)" "Cars per 1000 people"
10
USA 5951.13 1530.3 5.16 777
UK 2573.4 119.68 1.99 470
Italy 476.08 116.86 2 592
Germany 841.78 150.21 1.82 550
Canada 553.02 123.42 3.82 562
France 414.03 128.13 2.04 477
Russia 1575.44 114.69 0.8 178
Japan 1254.47 224.24 1.76 447
China 5100.6 228.02 0.3 17
India 1147.46 91.06 0.1 8
The program with the class being called carbonDioxide.java:
public class CarbonDioxideData {
private String country;
private double totalCO2;
private double roadCO2;
private double CO2PerPerson;
private int carsPerPerson;
public CarbonDioxideData() {
country = "blank_country";
totalCO2 = -1.0;
roadCO2 = -1.0;
CO2PerPerson = -1.0;
carsPerPerson = -1;
}
public String toString() {
String result = country;
result += " " + totalCO2;
result += " " + roadCO2;
result += " " + CO2PerPerson;
result += " " + carsPerPerson;
return result;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public double getTotalCO2() {
return totalCO2;
}
public void setTotalCO2(double totalCO2) {
this.totalCO2 = totalCO2;
}
public double getRoadCO2() {
return roadCO2;
}
public void setRoadCO2(double roadCO2) {
this.roadCO2 = roadCO2;
}
public double getCO2PerPerson() {
return CO2PerPerson;
}
public void setCO2PerPerson(double cO2PerPerson) {
CO2PerPerson = cO2PerPerson;
}
public int getCarsPerPerson() {
return carsPerPerson;
}
public void setCarsPerPerson(int carsPerPerson) {
this.carsPerPerson = carsPerPerson;
}
}
The program I am writing calling the two above, CarbonAnalysis.java:
import java.io.*;
import java.util.*;
public class CarbonAnalysis {
public static void main(String[]args){
//CarbonDioxideData c1 = new CarbonDioxideData();
//c1.setCountry("canada");
//System.out.println(c1);
Scanner userInput = new Scanner(System.in);
String fileName ="";
File inputFile = null;
Scanner fileReader = null;
while(fileReader==null){
try{
System.out.println("Enter input file name:");
fileName= userInput.next();
inputFile = new File(fileName);
fileReader = new Scanner(inputFile);
System.out.println("Successfully opening " + fileName);
}catch(IOException err){
System.out.println("Something went wrong");
System.out.println(err);
System.out.println("Please retry");
}
}
String testLine = fileReader.nextLine();
System.out.println(testLine);
int numberOfEntries = fileReader.nextInt();
System.out.println(numberOfEntries);
CarbonDioxideData[] array = new CarbonDioxideData[numberOfEntries];
for(int i =0;i<numberOfEntries;i++){
CarbonDioxideData c1 = new CarbonDioxideData();
String country = fileReader.next();
c1.setCountry(country);
double totalCO2 = fileReader.nextDouble();
c1.setTotalCO2(totalCO2);
double roadCO2 = fileReader.nextDouble();
c1.setRoadCO2(roadCO2);
double perPerson = fileReader.nextDouble();
c1.setCO2PerPerson(perPerson);
int cars = fileReader.nextInt();
c1.setCarsPerPerson(cars);
//System.out.println(c1);
array[i]=c1;
}
printArray(array);
emissionStats(array);
}
public static void printArray(CarbonDioxideData[] a){
for(int i=0; i<a.length;i++){
System.out.println(a[i]);
}
}
public static void emissionStats(CarbonDioxideData[] array){
for (int i = 0; i < array.length - 1; i++) {
// find index of smallest remaining value
int min = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[min]) {
min = j;
}
}
// swap smallest value its proper place, a[i]
swap(array, i, min);
}
}
public static void swap(CarbonDioxideData[] a, int i, int j) {
if (i != j) {
CarbonDioxideData temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
The error I am receiving when compiling:
CarbonAnalysis.java:68: error: bad operand types for binary operator '<'
if array[j] < array[min]
first type: CarbonDioxideData
Second type: CarbondDioxidedata
I am at a loss I have no idea how to get it to work. Any help appreciated
< , > binary operators can be used with primitive types.
public class CarbonDioxideData implements Comparable<CarbonDioxideData> {
private String country;
private double totalCO2;
private double roadCO2;
private double CO2PerPerson;
private int carsPerPerson;
#Override
public int compareTo(CarbonDioxideData that) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if (this == that) return EQUAL;
//Compare function according to your logic
if (this.totalCO2 == that.totalCO2) return EQUAL;
if (this.totalCO2 > that.totalCO2)
return AFTER;
else
return BEFORE;
}
}
Your comparison should be as
if (array[j].compareTo(array[min]) < 0) {
min = j;
}