Progressbar come outside bracket - java

i am making a progress bar for my school assignment. But when i run my code my progress bar come outside my bracket, but the = most be inside the bracket.
public static String repeatString(int number, String str) {
for (int i = 0; i < number; i++) {
System.out.print(str);
}
return str;
}
public static String formatPercentage(int percentage) {
if (percentage == 100) {
return "done";
}
else{
return percentage + "%";
}
}
public static String formatBar(int percentage, int length) {
int amount = percentage * length/ 100;
int size = length - amount;
return "[" + repeatString(amount, "=") + repeatString(size, " ") + "] " + formatPercentage(percentage);
}
this is the result:
[= ] 5%
== [= ] 20%
======= [= ] 70%
==========[= ] done
============== [= ] 70%

Change your repeatString method to the following: Don't print anything here, just build up the string and return it.
public static String repeatString(int number, String str) {
String pad = "";
for (int i = 0; i < number; i++) {
pad += str;
}
return pad;
}

Try this:
public class ProgressBar {
private int length;
private int maxSteps;
private int step;
private char symbol;
public ProgressBar(int length, int maxSteps, char symbol) {
this.length = length;
this.maxSteps = maxSteps;
this.symbol = symbol;
}
public void increment() {
increment(1);
}
public void increment(int numSteps) {
step+=numSteps;
print();
}
private void print() {
float percentage = (float)step/(float)maxSteps;
int numSymbols = (int) Math.floor((double)length*percentage);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < Math.min(numSymbols, length); i++) {
builder.append(symbol);
}
for (int i = Math.min(length, numSymbols); i < length; i++) {
builder.append(' ');
}
builder.append(String.format("[%s ]", symbol));
if (numSymbols >= length) {
builder.append(" done");
} else {
builder.append(String.format("%d %%", (int)(percentage*100)));
}
System.out.println(builder.toString());
}
public static void main(String [] args) {
ProgressBar bar = new ProgressBar(10, 50, '=');
bar.increment(10);
bar.increment(15);
bar.increment(20);
bar.increment(5);
System.out.println("Now exceeding max..");
bar.increment(10);
bar.increment(5);
}
}

Related

Why won't my bubble sort sort my array of objects?

I've created a program with an object called CarlysCatering. I'm trying to sort the CarlysCatering objects by number of guests.
I've tried using a bubble sort but I get an error message.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CarlysCatering[] event = new CarlysCatering[100];
event[0] = new CarlysCatering(10, "A547", "6874714145", 0);
event[1] = new CarlysCatering(100, "B527", "6874874945", 2);
event[2] = new CarlysCatering(50, "C546", "6874785145", 3);
event[3] = new CarlysCatering(40, "L577", "6874321485", 1);
event[4] = new CarlysCatering(70, "A111", "6874714145", 4);
event[5] = new CarlysCatering(90, "K222", "6874974855", 2);
event[6] = new CarlysCatering(11, "F798", "6875555555", 3);
event[7] = new CarlysCatering(17, "T696", "6474763898", 0);
//SORT
int selection = 0;
do {
System.out.println("1 - sort by eventID. 2 - sort by number of guests. 3 - sort by event type. 4 - quit");
selection = input.nextInt();
input.nextLine();
if(selection == 1) {
}
if(selection == 2) {
int n = event.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (event[j].getGuests() > event[j + 1].getGuests()) {
// swap arr[j+1] and arr[i]
CarlysCatering temp = event[j];
event[j] = event[j + 1];
event[j + 1] = temp;
}
}
}
}
} while (selection != 4);
//Print totals
event[0].getTotals(); event[1].getTotals(); event[2].getTotals(); event[3].getTotals(); event[4].getTotals(); event[5].getTotals(); event[6].getTotals(); event[7].getTotals();
}
////////////////////////////////////////////////////// STATIC METHODS //////////////////////////////////////////////////////////////////////
}
public class CarlysCatering {
public static final int PRICE_PER_GUEST_HIGH = 35;
public static final int PRICE_PER_GUEST_LOW = 32;
public static final int CUTOFF_VALUE_LARGE = 49;
private int guests;
private int totalPrice;
private String eventID;
private String phoneNumber;
private String eventType;
private boolean largeEvent;
///////////////////////////////////////////////////// CONSTRUCTORS //////////////////////////////////////////////////////////////////
CarlysCatering() {
this.guests = 0;
this.eventID = "A000";
this.phoneNumber = "0000000000";
}
CarlysCatering(int guests, String eventID, String phoneNumber, int eventType) {
this.guests = guests;
this.eventID = eventID;
//Phone Number formatting
String phoneNumber2 = "";
int count = 0;
for(int i = 0; i < phoneNumber.length(); i++) {
if (Character.isDigit(phoneNumber.charAt(i))) {
phoneNumber2 += phoneNumber.charAt(i);
count += 1;
}
}
if (count != 10) {
this.phoneNumber = "0000000000";
} else {
String phoneNumber3 = "(" + phoneNumber2.substring(0,3) + ") " + phoneNumber2.substring(3,6) + "-" + phoneNumber2.substring(6,10);
this.phoneNumber = phoneNumber3;
}
//Event type formatting
final String[] eventString = new String[5];
eventString[0] = "wedding"; eventString[1] = "baptism"; eventString[2] = "birthday"; eventString[3] = "corporate"; eventString[4] = "other";
if(eventType > -1 && eventType < 5) {
this.eventType = eventString[eventType];
} else {
this.eventType = eventString[4];
}
}
///////////////////////////////////////////////////////// SETTERS AND GETTERS /////////////////////////////////////////////////
//Setters
public void setEventID(String eventID) {
this.eventID = eventID;
}
public void setGuests(int guests) {
this.guests = guests;
}
public void setPhoneNumber(String phoneNumber) {
String phoneNumber2 = "";
int count = 0;
for (int i = 0; i < phoneNumber.length(); i++) {
if (Character.isDigit(phoneNumber.charAt(i))) {
phoneNumber2 += phoneNumber.charAt(i);
count += 1;
}
}
if (count != 10) {
this.phoneNumber = "0000000000";
} else {
String phoneNumber3 = "(" + phoneNumber2.substring(0, 3) + ") " + phoneNumber2.substring(3, 6) + "-" + phoneNumber2.substring(6, 10);
this.phoneNumber = phoneNumber3;
}
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
//Getters
public int getTotalPrice() {
return totalPrice;
}
public int getGuests() {
return guests;
}
public String getEventID() {
return eventID;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getEventType() {
return eventType;
}
/////////////////////////////////////////////////////// ADDITIONAL METHODS ///////////////////////////////////////////////////////////////////
public void isLargeEvent() {
if (this.guests > CUTOFF_VALUE_LARGE) {
largeEvent = true;
System.out.println("Yes this is a large event.");
} else {
largeEvent = false;
System.out.println("This is not a large event");
}
}
public void getTotals() {
boolean largeEvent = false;
if(this.guests > CUTOFF_VALUE_LARGE) {
largeEvent = true;
this.totalPrice = this.guests * PRICE_PER_GUEST_HIGH;
} else {
largeEvent = false;
this.totalPrice = this.guests * PRICE_PER_GUEST_LOW;
}
System.out.println("The number of guests attending event " + this.eventID + " " + this.eventType + " is: " + this.guests + ". The total price is $" + this.totalPrice);
System.out.println("Large event: " + largeEvent);
System.out.println("The phone number on file is " + this.phoneNumber);
}
// Static methods
public static void showMotto() {
System.out.println("*****Carly's makes the food that makes it a party.*****");
}
}
The error message I get when I try to sort by guests is Exception in thread "main" java.lang.NullPointerException and then error code exit -1. The line that's causing the error is:
if (event[j].getGuests() > event[j + 1].getGuests()) {
You create an Array with the size 100.
After that, you fill it from index 0 to 7.
Every other place of the array remains null but the length is 100.
Then, you try to sort the array.
This throws a NullPointerException when you try to dereference (access) the 8. element:
event[j+1].getGuests()
I think you should use a smaller array(size 8) or a List.

Java - Matrix of complex numbers

I want to create a class ComplexMatrix that has field a array[NxN] of type ComplexNumber. I already made a ComplexNumber class as you can see below:
public class ComplexNumber {
private double real;
private double img;
// Getters and setters
public double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getImg() {
return img;
}
public void setImg(double img) {
this.img = img;
}
// Constructor
public ComplexNumber(double real, double img) {
this.real = real;
this.img = img;
}
// Add
public ComplexNumber addComp(ComplexNumber num) {
ComplexNumber num1 = new ComplexNumber(real + num.real, img + num.img);
return num1;
}
// Subtract
public ComplexNumber subtractComp(ComplexNumber num) {
ComplexNumber num1 = new ComplexNumber(real - num.real, img - num.img);
return num1;
}
// Multiply
public ComplexNumber multiplyComp(ComplexNumber num) {
ComplexNumber num1 = new ComplexNumber(real*num.real-img*num.img,real*num.img+img*num.real);
return num1;
}
// Is Equals
boolean equals(ComplexNumber num) {
ComplexNumber num1 = new ComplexNumber(real, img);
if (num.real == num1.real && num.img == num1.img) {
return true;
} else {
return false;
}
}
#Override
public String toString() {
if (img > 0) {
return getReal() + " + " + Math.abs(getImg()) + "i";
}
if (img < 0) {
return getReal() + " - " + Math.abs(getImg()) + "i";
}
if (real==0) {
return getImg() + "i";
}
if (img==0) {
return getReal() + "";
}
return null;
}
}
that has some methods and its own toString that prints as follows:
3.51 + 1.87i
2.35 - 5.61i
-8.45 + 2.65i
The implemented ComplexMatrix has an array [M][N] as a field, and the cronstructor public ComplexMatrix(int rows, int cols) gives the array
random numbers from one to ten using the method computeRandom. Then a
toString() functions (which also implemets toSting() from ComplexNumber class) , should print the random numbers array. A desired print of ComplexMatrix would be:
[1.24 + 2.55i, -0.32 + 2.00i, 1.35 - 5.88i;
-5.71 - 5.91i, 0.29 – 9.14i, 0.00 + 3.51i;
6.44 + 0.00i, -3.51 – 0.67i, 2.10 + 4.20i;]
Here is ComplexMatrix class:
import java.util.Random;
public class ComplexMatrix {
private ComplexNumber[][] complexArray;
// Default Constructor
public ComplexMatrix() {
super();
this.complexArray = null;
}
// Copy Constructor
public ComplexMatrix(ComplexMatrix original) {
super();
original.complexArray = complexArray;
}
private Random rand = new Random();
private double computeRandom() {
int randomNum = (int) ((rand.nextDouble() - 0.5) * rand.nextInt(20) * 100);
return randomNum / 100.0;
}
// Random Numbers Constructor
public ComplexMatrix(int rows, int cols) {
double real = 0;
double img = 0;
ComplexNumber[][] complexArray= new ComplexNumber[rows][cols];
for (int i = 0; i < rows; i++) {
System.out.print("\n");
for (int j = 0; j < cols; j++) {
real = computeRandom();
img = computeRandom();
complexArray[i][j] = new ComplexNumber(real, img);
//edw peiramatizomai..to print 8a ginetai sthn toString()
System.out.print(complexArray[i][j].toString());
System.out.print("\t");
}
}
}
#Override
public String toString() {
int rows = 0,cols = 0;
//ComplexNumber[][] complexArray= new ComplexNumber[rows][cols];
ComplexMatrix s = new ComplexMatrix(rows,cols);
String out = "[";
//????????????????????????????????????
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++) {
//????????
out = s.toString();
}
out += "]";
return out;
}
}
I'm just going to give pseudo-code (partly on the assumption that this is an assignment). But hopefully this gives you enough to get going with an implementation without just plain giving the solution.
#Override
public String toString() {
out = "[";
for (row : rows) {
if (notFirstRow) {
out += "\n"; // New line
}
for (column : columns) {
if (notFirstColumn) {
out += ", ";
}
out += matrix[row][column].toString();
}
}
out += "]";
return out;
}
Warning, I make no claims that this is optimal, or that there aren't better ways to format a matrix (or complex numbers)... But if you can flesh this out to actually compile I suspect you'll have what you're after.
I think the main problem here is to print according to your desired format. Here is sample code to achieve this:
#Override
public String toString() {
StringBuilder out = new StringBuilder();
out = out.append("[");
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
out.append(String.valueOf(matrix[row][column]));
//Populate according to whether last column or not.
out.append(column != columns - 1 ? ", " : ";");
}
out.append(row != rows - 1 ? "\n" : "");
}
out.append("]");
return out.toString();
}
Just remember, for nested arrays you have an Arrays.deepToString method available in standard library.

java.lang.NullPointerException appearing for no reason [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have made a program inside of which, there is a specific method that makes sure that all of the objects in an array that point to null point to a blank space. For some reason, whenever I run the code, it gives me a java.lang.NullPointerException.
I understand what a NullPointerException is, which is why I added the if statement, so that it wouldn't give the error, but it still does
Code:
public class TextGraphics {
public static void main(String[] args) {
displaySize size = new displaySize(5,5);
displaySize.output(5,3,size,"H");
displaySize.run(size);
}
}
class displaySize {
public static int indent;
public static int sizeX = 0;
public static int sizeY = 0;
public displaySize() {
}
public displaySize(int screenX, int screenY) {
sizeX = screenX;
sizeY = screenY;
indent = sizeX;
}
public static void output(int x, int y, displaySize size, String print) {
rarray(size)[x + y * size.sizeX] = print;
}
public static String[] rarray(displaySize size) {
String [] display;
return display = new String[sizeX * sizeY];
}
public static void run(displaySize size) {
int next = 0;
for (int i = 0; i < sizeY; i++) {
for (int b = 0; b < indent; b++) {
next++;
if(rarray(size)[next].equals(null) )
{
System.out.print( rarray(size)[next] + " ");
rarray(size)[next] = " ";
}
System.out.print( rarray(size)[next] + " ");
}
System.out.println("/n");
}
}
}
first problem used .equals(null) instead of == null
second problem your code throws a arrayoutofindex because your next++ was in the wrong for loop
finally your new line character was wrong its \n not /n
corrected code
public class TextGraphics {
public static void main(String[] args) {
displaySize size = new displaySize(5,5);
displaySize.output(5,3,size,"H");
displaySize.run(size);
}
}
class displaySize {
public static int indent;
public static int sizeX = 0;
public static int sizeY = 0;
public displaySize() {
}
public displaySize(int screenX, int screenY) {
sizeX = screenX;
sizeY = screenY;
indent = sizeX;
}
public static void output(int x, int y, displaySize size, String print) {
rarray(size)[x + y * size.sizeX] = print;
}
public static String[] rarray(displaySize size) {
String [] display;
return display = new String[sizeX * sizeY];
}
public static void run(displaySize size) {
int next = 0;
for (int i = 0; i < sizeY; i++) {
next++;
for (int b = 0; b < indent; b++) {
if(rarray(size)[next]==(null) )
{
rarray(size)[next] = " ";
System.out.print( rarray(size)[next] + " ");
}
System.out.print( rarray(size)[next] + " ");
}
System.out.println("\n");
}
}
}

user input still stored after exceeding array length

Can someone see why the user can enter more than 27 apple, blueberry, or peanut pies? Even after declaring a final int for the max number of each type of pie.
The object here is to continually prompt the user for type of pie until the user wants to quit. Each time one of the valid inputs is entered it is stored in it's own array. After the user has indicated they are finished, calculations are done and a message is printed.
import javax.swing.JOptionPane;
public class CalcPieProfit {
public static void main(String[] args) {
final int MAX_PER_TYPE = 27;
int appleTotal = 0;
int blueberryTotal = 0;
int peanutTotal = 0;
String typeOfPie = getPieType();
while (!typeOfPie.equalsIgnoreCase("q")) {
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
appleTotal++;
}
else if (typeOfPie.equalsIgnoreCase("blueberry")) {
String[] blueberryArray = fillBlueberry(typeOfPie, MAX_PER_TYPE);
blueberryTotal++;
}
else if (typeOfPie.equalsIgnoreCase("peanut")) {
String[] peanutArray = fillPeanut(typeOfPie, MAX_PER_TYPE);
peanutTotal++;
}
typeOfPie = getPieType();
}
if (typeOfPie.equalsIgnoreCase("q")) {
int totalPies = calcTotalPies(appleTotal, blueberryTotal, peanutTotal);
double profit = calcProfit(appleTotal, blueberryTotal, peanutTotal);
printReport(totalPies, appleTotal, blueberryTotal, peanutTotal, profit);
}
}
public static String getPieType() {
String pieType;
do {
try {
pieType = JOptionPane.showInputDialog("Enter a pie type:");
}
catch (NumberFormatException e) {
pieType = "";
}
if (!pieType.equalsIgnoreCase("apple") && !pieType.equalsIgnoreCase("blueberry") &&
!pieType.equalsIgnoreCase("peanut") && !pieType.equalsIgnoreCase("q")) {
JOptionPane.showMessageDialog(null, "Enter 'apple', 'blueberry', 'peanut', or 'q' only.");
}
} while (!pieType.equalsIgnoreCase("apple") && !pieType.equalsIgnoreCase("blueberry") &&
!pieType.equalsIgnoreCase("peanut") && !pieType.equalsIgnoreCase("q"));
return pieType;
}
public static String[] fillApple(String typeOfPie, int MAX_PER_TYPE) {
String[] appleArray = new String[MAX_PER_TYPE];
for (int i = 0; i < appleArray.length; i++) {
appleArray[i] = typeOfPie;
}
return appleArray;
}
public static String[] fillBlueberry(String typeOfPie, int MAX_PER_TYPE) {
String[] blueberryArray = new String[MAX_PER_TYPE];
for (int i = 0; i < blueberryArray.length; i++) {
blueberryArray[i] = typeOfPie;
}
return blueberryArray;
}
public static String[] fillPeanut(String typeOfPie, int MAX_PER_TYPE) {
String[] peanutArray = new String[MAX_PER_TYPE];
for (int i = 0; i < peanutArray.length; i++) {
peanutArray[i] = typeOfPie;
}
return peanutArray;
}
public static int calcTotalPies(int appleTotal, int blueberryTotal, int peanutTotal) {
int total = appleTotal + blueberryTotal + peanutTotal;
return total;
}
public static double calcProfit (int appleTotal, int blueberryTotal, int peanutTotal) {
final double APPLE_PROFIT = 5.94;
final double BLUEBERRY_PROFIT = 5.89;
final double PEANUT_PROFIT = 6.95;
double profit = (APPLE_PROFIT * appleTotal) + (BLUEBERRY_PROFIT * blueberryTotal) +
(PEANUT_PROFIT * peanutTotal);
return profit;
}
public static void printReport(int totalPies, int appleTotal, int blueberryTotal, int peanutTotal, double profit) {
if (totalPies > 0) {
JOptionPane.showMessageDialog(null,
"Pie Report\n\n" +
"Total pies: " + totalPies +
"\nTotal of apple pie: " + appleTotal +
"\nTotal of blueberry pie: " + blueberryTotal +
"\nTotal of peanut butter pie: " + peanutTotal +
"\nTotal profit: $" + String.format("%.2f", profit));
}
else {
JOptionPane.showMessageDialog(null, "Enjoy your day off.");
}
}
}
You are not really using the String[]s appleArray, blueberryArray and peanutArray - they are created in their respective method but not used anywhere else. For calculating the profits, you are (rightfully) only the total variables.
Instead of
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
appleTotal++;
}
you should do something like
if (typeOfPie.equalsIgnoreCase("apple")) {
if (appleTotal >= MAX_PER_TYPE) {
JOptionPane.showMessageDialog(null, "Too many apples.");
} else {
appleTotal++;
}
}
(and the same for other pie types).
You're redeclaring the pie arrays each time you go to add them.
public static String[] fillApple(String typeOfPie, int MAX_PER_TYPE) {
String[] appleArray = new String[MAX_PER_TYPE];
for (int i = 0; i < appleArray.length; i++) {
appleArray[i] = typeOfPie;
}
return appleArray;
}
Each time you call this method, a new "appleArray" is generated. If you want it to persist between calls to this method, declare the appleArray as private static outside of the loop, and reference that instead.

Having trouble calling another class that reads a txt file into an array that is sorted in the program(band operand error)

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;
}

Categories

Resources