I have an enum
Customer("Customer"),
BankName("Bank Name"),
AccountNumber("Account Number"),
Amount("Available Amount");
I have an array of ints, that contains the right order
private static int[] realOrder;
I have a method that sorts enum in the right order
public static void configureColumns(Column... newOrder)
{
realOrder = new int[values().length];
for (Column column : values())
{
realOrder[column.ordinal()] = -1;
boolean isFound = false;
for (int i = 0; i < newOrder.length; i++)
{
if (column == newOrder[i])
{
if (isFound)
{
throw new IllegalArgumentException("Column '" + column.columnName + "' is already configured.");
}
realOrder[column.ordinal()] = i;
isFound = true;
}
}
}
}
And when i call that method like that
Column.configureColumns(Column.Amount, Column.AccountNumber, Column.BankName);
I want it to be printed
* Available Amount
* Account Number
* Bank Name
I have a method, that returns a linked list according to the realOrder indexes
public static List<Column> getVisibleColumns()
{
List<Column> result = new LinkedList<>();
int index;
for(int i = 0; i < realOrder.length; i++)
{
if(realOrder[i]!=-1)
{
index = realOrder[i];
result.add(index, Column.values()[index]);
}
}
return result;
}
But i get java.lang.IndexOutOfBoundsException: Index: 2, Size: 0 because i should start from 0 to fill the array. If i sort the realOrder array from smallest to greatest, it works, but not in way it expected. How can i solve it?
It seems you want getVisibleColumns() to return the values exactly as they were given to configureColumns(), so why not just remember that?
public enum Column {
Customer("Customer"),
BankName("Bank Name"),
AccountNumber("Account Number"),
Amount("Available Amount");
private static Column[] realOrder;
private final String columnName;
private Column(String columnName) {
this.columnName = columnName;
}
public String getColumnName() {
return this.columnName;
}
public static void configureColumns(Column... newOrder) {
realOrder = newOrder.clone();
}
public static List<Column> getVisibleColumns() {
return Collections.unmodifiableList(Arrays.asList(realOrder));
}
}
If you also need a to know the order index of a particular Column, don't create a separate array to store that. Just add an extra field to the enum:
private int orderIndex = -1;
Then update the value when configuring:
public static void configureColumns(Column... newOrder) {
realOrder = newOrder.clone();
for (Column column : values())
column.orderIndex = -1;
for (int i = 0; i < newOrder.length; i++)
newOrder[i].orderIndex = i;
}
Related
There is a code for the BigestCountries class.
It consists of 2 arrays:
private String[][] biggestCountries; - holds country name and the continent, e.g. biggestCountries[CHINA][COUNTRY_NAME] = "China"; biggestCountries[CHINA][COUNTRY_CONTINENT] = "Asia";
private int[][] countryData; - holds populations and year founded, e.g. countryData[CHINA][COUNTRY_POPULATION] = 1433783686; countryData[CHINA][COUNTRY_AGE_FOUNDED] = 1949;
public String[] getCountriesFoundedBetween(int min, int max){
int countriesMatched;
countriesMatched = 0;
String[] countriesFoundedBetween;
if(biggestCountries == null || biggestCountries.length == 0){
return null;
}
for(int i = 0; i < biggestCountries.length; i++){
if(countryData[i][COUNTRY_AGE_FOUNDED] >= min && countryData[i][COUNTRY_AGE_FOUNDED] <= max){
System.out.println(String.format("%d %s", countryData[i][COUNTRY_AGE_FOUNDED], biggestCountries[i][COUNTRY_NAME]));
countriesMatched++;
}
}
if(countriesMatched > 0){
countriesFoundedBetween = new String[countriesMatched];
} else {
return null;
}
for(int i = 0; i < biggestCountries.length; i++) { // outer loop for countries array length of NUMBER_OF_COUNTRIES
String countryMatched = null;
System.out.println("biggestCountries[i] " + biggestCountries[i][COUNTRY_NAME]);
if(countryData[i][COUNTRY_AGE_FOUNDED] >= min && countryData[i][COUNTRY_AGE_FOUNDED] <= max){
for(int j = 0; j < countriesFoundedBetween.length; j++){ // how to escape inner loop?
countryMatched = biggestCountries[i][COUNTRY_NAME];
countriesFoundedBetween[j] = countryMatched;
System.out.println("countriesFoundedBetween: " + countriesFoundedBetween[j] + "; biggestCountries[i][COUNTRY_NAME]: " + biggestCountries[i][COUNTRY_NAME]);
}
}
}
return countriesFoundedBetween;
}
Unfortunately, It cannot escape from the inner loop and re-writes the matched country to all rows of the newly-generated array.
The method getCountriesFoundedBetween() can be implemented differently, without the need for nested loops, as follows.
private static String[] getCountriesFoundedBetween(int min, int max) {
if (max < min) {
throw new IllegalArgumentException("'max' less than 'min'");
}
String[] countriesFoundedBetween;
int countriesMatched = 0;
int[] indexes = new int[biggestCountries.length];
if (biggestCountries != null && biggestCountries.length > 0) {
for (int i = 0; i < biggestCountries.length; i++) {
if(countryData[i][COUNTRY_AGE_FOUNDED] >= min &&
countryData[i][COUNTRY_AGE_FOUNDED] <= max) {
indexes[countriesMatched++] = i;
}
}
countriesFoundedBetween = new String[countriesMatched];
for (int i = 0; i < countriesMatched; i++) {
countriesFoundedBetween[i] = biggestCountries[indexes[i]][COUNTRY_NAME];
}
}
else {
countriesFoundedBetween = new String[0];
}
return countriesFoundedBetween;
}
The above code also returns an empty array rather than null which is preferable for methods that return arrays.
Here is a complete example using population to determine the biggest countries.
public class Countrys {
private static final int CHINA = 0;
private static final int INDIA = 1;
private static final int U_S_A = 2;
private static final int INDONESIA = 3;
private static final int PAKISTAN = 4;
private static final int BRAZIL = 5;
private static final int NIGERIA = 6;
private static final int BANGLADESH = 7;
private static final int RUSSIA = 8;
private static final int MEXICO = 9;
private static final int COUNTRY_NAME = 0;
private static final int COUNTRY_CONTINENT = 1;
private static final int COUNTRY_POPULATION = 0;
private static final int COUNTRY_AGE_FOUNDED = 1;
private static int[][] countryData = new int[][]{{1_427_647_786, 1949},
{1_352_642_280, 1950},
{ 328_239_523, 1776},
{ 273_523_615, 1945},
{ 220_892_340, 1947},
{ 210_147_125, 1889},
{ 206_139_589, 1960},
{ 164_689_383, 1971},
{ 144_384_244, 1991},
{ 128_932_753, 1810}};
private static String[][] biggestCountries = new String[][]{{"China" , "Asia"},
{"India" , "Asia"},
{"U.S.A." , "North America"},
{"Indonesia" , "Asia"},
{"Pakistan" , "Asia"},
{"Brazil" , "South America"},
{"Nigeria" , "Africa"},
{"Bangladesh", "Asia"},
{"Russia" , "Europe"},
{"Mexico" , "North America"}};
private static String[] getCountriesFoundedBetween(int min, int max) {
if (max < min) {
throw new IllegalArgumentException("'max' less than 'min'");
}
String[] countriesFoundedBetween;
int countriesMatched = 0;
int[] indexes = new int[biggestCountries.length];
if (biggestCountries != null && biggestCountries.length > 0) {
for (int i = 0; i < biggestCountries.length; i++) {
if(countryData[i][COUNTRY_AGE_FOUNDED] >= min &&
countryData[i][COUNTRY_AGE_FOUNDED] <= max) {
indexes[countriesMatched++] = i;
}
}
countriesFoundedBetween = new String[countriesMatched];
for (int i = 0; i < countriesMatched; i++) {
countriesFoundedBetween[i] = biggestCountries[indexes[i]][COUNTRY_NAME];
}
}
else {
countriesFoundedBetween = new String[0];
}
return countriesFoundedBetween;
}
public static void main(String[] args) {
String[] result = getCountriesFoundedBetween(1950, 1980);
System.out.println(Arrays.toString(result));
}
}
Running the above code produces the following output:
[India, Nigeria, Bangladesh]
If you name a Class BigestCountries still it has an attribute biggestCountries which is an array, holds information about biggest countries, I think you are not utilizing the potential of OO.
You can use Class to represent the data of a Country. With data encapsulation, you can get rid of nested array thus nested loop and control flow statement (break, continue etc), lookup index constant, keep sync-ing the index between biggestCountries and countryData etc.
Your code doing the same task twice. The first loop count the matched country and initialize a array. The second loop actually put the matched country name to the array.
Java collection framework provide data structure with dynamic size. I use ArrayList here
I think ageFound should be named yearFound?
Refactored Your code
Country.java
public class Country {
private String name;
private int population;
private int yearFound;
private String continent;
public Country(String name, String continent, int year, int population) {
this.name = name;
this.population = population;
this.continent = continent;
this.yearFound = year;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
public int getYearFound() {
return yearFound;
}
public void setYearFound(int yearFound) {
this.yearFound = yearFound;
}
#Override
public String toString() {
return "Country [name=" + name + ", population=" + population + ", yearFound=" + yearFound + ", continent="
+ continent + "]";
}
}
BiggestCountries.java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class BiggestCountries {
private List<Country> countries = new ArrayList<Country>() {
{
add(new Country("China", "Asia", 1949, 1433783686));
add(new Country("Canada", "North America", 1867, 37590000));
add(new Country("United States", "North America", 1776, 328200000));
}
};
public List<Country> getCountriesFoundedBetween(int min, int max) {
List<Country> matchedCountry = new ArrayList<Country>();
Iterator<Country> itrCoutnry = countries.iterator();
while (itrCoutnry.hasNext()) {
Country country = itrCoutnry.next();
int yearFound = country.getYearFound();
if (min < yearFound && max > yearFound) {
matchedCountry.add(country);
}
}
return matchedCountry;
}
}
Test Run
public static void main(String[] args) {
List<Country> matchedCountries = new BiggestCountries().getCountriesFoundedBetween(1700, 1899);
System.out.println(matchedCountries);
}
Result
[Country [name=Canada, population=37590000, yearFound=1867, continent=North America], Country [name=United States, population=328200000, yearFound=1776, continent=North America]]
My findmaxprice method returns the index of the first Car in the array with the maximum price. If it is not found, -1 is returned.
As far as I know, return will stop the for loop. Any advice on how to avoid it while keep the loop search for max price?
public int findmaxprice() {
double max =0;
for(int i =0; i < nCars; i++) {
if(max <= Cars[i].getPrice()) {
max = Cars[i].getPrice();
return i; //the problem is here
}
}
return -1;
}
You almost answered yourself - just don't return in the for loop.
public int findmaxprice() {
double max =0;
int maxIndex = -1;
for( int i =0; i < nCars; i++) {
if(max <= Cars[i].getPrice()) {
max = Cars[i].getPrice();
maxIndex = i;
}
}
return maxIndex;
}
Move the return statement outside of the loop
findmaxprice method: returns the index of the first Car in the array with the maximum price. If it is not found, -1 is returned. as far as i know, return will stop the for loop , any advice on how to avoid it while keep the loop search for max price ?
public int findmaxprice() {
double max =0;
for( int i =0; i < nCars; i++) {
if(max <= Cars[i].getPrice()) {
max = Cars[i].getPrice();
}
}
if(max != 0){
return max;
} else {
return -1;
}
}
The below method will fix your issue. Also, it gives you ability to specify a minimum price above which the car price will be considered for max calculation. You can keep this 0 in function call like findMaxPrice(0)if no such boundation needed.
public int findMaxPrice(int min) {
double max = min;
int maxPriceCarIndex = -1;
for (int i = 0; i < nCars; i++) {
if (max <= Cars[i].getPrice()) {
max = Cars[i].getPrice();
maxPriceCarIndex = i; //reassign the index here
}
}
return maxPriceCarIndex;
}
Maybe you just need the "most expensive" car and not the index of the car, then you could consider using streams
import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
public class Test {
public static void main(String[] args) {
new Test().testGetMostExpensiveCar();
}
private void testGetMostExpensiveCar() {
// test null array
Car[] cars = null;
Car mostExpensive = getMostExpensiveCar(cars);
System.out.println(mostExpensive); // prints null
// test empty array
cars = new Car[10];
mostExpensive = getMostExpensiveCar(cars);
System.out.println(mostExpensive); // prints null
//test array with cars
cars[0] = new Car(10.0);
cars[5] = new Car(20.0);
cars[8] = new Car(30.0);
cars[8] = new Car(30.0);
mostExpensive = getMostExpensiveCar(cars);
System.out.println(mostExpensive);// prints Car [price=30.0]
}
/**
* #param cars
* #return the most Expensive car, null if the array is empty or no car is in
* the array
*/
public Car getMostExpensiveCar(Car[] cars) {
if (cars == null) {
return null;
}
return Arrays.stream(cars) // creates a Stream<Car> (take a look at e.g. https://www.baeldung.com/java-8-streams)
.filter(Objects::nonNull) // because there can be "null" values in the array
.max(Comparator.comparing(Car::getPrice)) // compares the car by price asc
.orElse(null); // return null if no element is found
}
private class Car {
private double price;
public Car(double price) {
super();
this.price = price;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
#Override
public String toString() {
return "Car [price=" + price + "]";
}
}
}
In my program I have a pair class:
class Pair {
public int ind = 0;
public String letter = "";
public Pair(int a, String b) {
ind = a; //index
letter = b;
}
}
how do I set the index (ind) of an element in an arraylist of Pairs? I have tried
RightMotor.ind.set(j, i);
and
LeftMotor.set(j, i).ind;
but they don't seem to work.
First you need to 'get' the Pair instance, like:
Pair pair = LeftMotor.get(i);
then you can change its fields:
pair.ind = j;
This can also be done in one line:
LeftMotor.get(i).ind = j;
Hint 1: this is not changing the index (position) of the instance in the list, LeftMotor.get(i) will still return the same element. i and ind are two completely disjunct values.
Hint 2: normally it is better to have private fields and have a method (setter) to change the fields (encapsulation):
class Pair {
private int ind = 0;
private String letter = "";
public Pair(int a, String b) {
ind = a; //index
letter = b;
}
public void setInd(int newInd) {
ind = newInd;
}
}
Hint 3: just to be clear, just because it is called ind it is not the index (position) of the list. It is a whole different question if you want to change the order of the elements in the list.
You want to make those instance variables private, then getters/setters to access/modify them. This allows you to safely and securely manipulate the data with a reduced chance of bleedover (which can crash your program or cause unintended consequences).
Within your class:
class Pair {
private int ind = 0;
private String letter = "";
public Pair(int index, String letter) {
ind = index;
letter = letter;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getLetter() {
return this.letter;
}
public void setLetter(String letter) {
this.letter = letter;
}
public void setIndexAndLetter(int index, String letter) {
this.index = index;
this.letter = letter;
}
}
Elsewhere in your program:
Pair rightMotor = new Pair(1, "a");
Pair leftMotor = new Pair(2, "b");
Pair middleMotor = new Pair(0, "");
rightMotor.setInd(3);
leftMotor.setLetter("d");
middleMotor.setIndAndLetter(rightMotor.getInd() + leftMotor.getInd(), "z");
You have to create a Pair instance using the Pair constructor before adding it to the ArrayList:
RightMotor.add(new Pair(i,j)); // assuming i is an int and j is a String
If you want to replace the Pair stored in a given index use:
RightMotor.set(index,new Pair(i,j));
If you want to change an existing Pair stored in the ArrayList:
RightMotor.get(index).setInd(newValue);
This will require a setter method in your Pair class:
public void setInd (int i) {
ind = i;
}
So I think that you could solve this in a couple of different ways... however I think I know what you are trying to do.... I feel like you are trying to keep the ArrayList and the Pair index synchronized... either way you will need a helper method to accomplish this. I agree with hendripd that you should use private variables and utilize the getters and setters. However this is my solution.
Pair:
public class Pair implements Comparable<Pair> {
private int index = 0;
private String letter = "";
public Pair(int index, String letter) {
this.index = index;
this.letter = letter;
}
public Pair(Pair pair) {
this.index = pair.getIndex();
this.letter = pair.getLetter();
}
#Override
public int compareTo(Pair pair) {
if (this.index > pair.index) {
return 1;
} else if (this.index < pair.index) {
return -1;
} else {
return 0;
}
}
#Override
public String toString() {
return this.index + " " + this.letter;
}
public int getIndex() {
return this.index;
}
public String getLetter() {
return this.letter;
}
public void setIndex(int index) {
this.index = index;
}
public void setLetter(String letter) {
this.letter = letter;
}
}
Main:
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static ArrayList<Pair> rightMotor;
public static void main(String[] args) {
rightMotor = new ArrayList<Pair>();
rightMotor.add(new Pair(0, "a"));
rightMotor.add(new Pair(1, "b"));
setIndex(rightMotor, 0, 1);
// If you choose to go with the second option utilizing Comparable<Pair>
// Collections.sort(rightMotor);
for (Pair pair : rightMotor) {
System.out.println(pair.toString());
}
}
public static void setIndex(ArrayList<Pair> motor, int oldIndex, int newIndex) {
Pair tempPair = new Pair(motor.get(oldIndex));
if (oldIndex < newIndex) {
for (int i = oldIndex; i < newIndex; i++) {
motor.set(i, motor.get(i + 1));
motor.get(i).setIndex(i);
}
} else if (oldIndex > newIndex) {
for (int i = oldIndex; i > newIndex; i--) {
motor.set(i, motor.get(i - 1));
motor.get(i).setIndex(i);
}
}
tempPair.setIndex(newIndex);
motor.set(newIndex, tempPair);
}
}
Note that the Pair class implements comparable... you could use Collections.Sort(rightMotor) which then you would only need to fix the indexes of the instances... i.e.
public static void setIndex(ArrayList<Pair> motor, int oldIndex, int newIndex) {
motor.get(oldIndex).setIndex(newIndex);
if (oldIndex < newIndex) {
for (int i = oldIndex; i < newIndex; i++) {
motor.get(i + 1).setIndex(i);
}
} else if (oldIndex > newIndex) {
for (int i = oldIndex; i > newIndex; i--) {
motor.get(i - 1).setIndex(i);
}
}
}
Or... you can use the original one I posted which also handles the sorting at the same time. This keeps your Arraylist in numerical order by index either way.
Test casing:
rightMotor.add(new Pair(0, "a"));
rightMotor.add(new Pair(1, "b"));
rightMotor.add(new Pair(2, "c"));
rightMotor.add(new Pair(3, "d"));
rightMotor.add(new Pair(4, "e"));
rightMotor.add(new Pair(5, "f"));
setIndex(rightMotor, 0, 1);
setIndex(rightMotor, 3, 1);
setIndex(rightMotor, 4, 3);
outputs this result:
0 b
1 d
2 a
3 e
4 c
5 f
My assignment asks me to make a TV show program, where I can input shows, delete, modify and sort them. What I'm stuck on is the sorting part. With the show, it asks for the name, day a new episode premieres, and time. Those are the keys I need to sort it by.
The program prompts the user to input one of those keys, then the program needs to sort (sorting by day will sort alphabetically).
I made a class and used an array. Here is the class:
public class showInfo
{
String name;
String day;
int time;
}
And the method to sort by time in the code:
public static void intSort()
{
int min;
for (int i = 0; i < arr.length; i++)
{
// Assume first element is min
min = i;
for (int j = i+1; j < arr.length; j++)
{
if (arr[j].time < arr[min].time)
{
min = j;
}
}
if (min != i)
{
int temp = arr[i].time;
arr[i].time = arr[min].time;
arr[min].time = temp;
}
}
System.out.println("TV Shows by Time");
for(int i = 0; i < arr.length; i++)
{
System.out.println(arr[i].name + " - " + arr[i].day + " - " + arr[i].time + " hours");
}
}
When I call it and output it in the main, it only shows "TV Shows by Time" and not the list. Why is this?
Also, I need to make ONE method that I will be able to use to sort both the day AND the name (both Strings). How can I do this without using those specific arrays (arr[i].name, arr[i].day) in the method?
Any help would be greatly appreciated! Thanks in advance!
In this part of your code
if (min != i) {
int temp = arr[i].time;
arr[i].time = arr[min].time;
arr[min].time = temp;
}
You're just changing the time when you should move the whole object instead. To fix it, the code must behave like this:
if (min != i) {
//saving the object reference from arr[i] in a temp variable
showInfo temp = arr[i];
//swapping the elements
arr[i] = arr[min];
arr[min] = temp;
}
I̶t̶ ̶w̶o̶u̶l̶d̶ ̶b̶e̶ ̶b̶e̶t̶t̶e̶r̶ ̶t̶o̶ ̶u̶s̶e̶ ̶ Arrays#sort ̶w̶h̶e̶r̶e̶ ̶y̶o̶u̶ ̶p̶r̶o̶v̶i̶d̶e̶ ̶a̶ ̶c̶u̶s̶t̶o̶m̶ ̶̶C̶o̶m̶p̶a̶r̶a̶t̶o̶r̶̶ ̶o̶f̶ ̶t̶h̶e̶ ̶c̶l̶a̶s̶s̶ ̶b̶e̶i̶n̶g̶ ̶s̶o̶r̶t̶e̶d̶ ̶(̶i̶f̶ ̶y̶o̶u̶ ̶a̶r̶e̶ ̶a̶l̶l̶o̶w̶e̶d̶ ̶t̶o̶ ̶u̶s̶e̶ ̶t̶h̶i̶s̶ ̶a̶p̶p̶r̶o̶a̶c̶h̶)̶.̶ ̶S̶h̶o̶r̶t̶ ̶e̶x̶a̶m̶p̶l̶e̶:̶
showInfo[] showInfoArray = ...
//your array declared and filled with data
//sorting the array
Arrays.sort(showInfoArray, new Comparator<showInfo>() {
#Override
public int compare(showInfo showInfo1, showInfo showInfo2) {
//write the comparison logic
//basic implementation
if (showInfo1.getTime() == showInfo2.getTime()) {
return showInfo1.getName().compareTo(showInfo2.getName());
}
return Integer.compare(showInfo1.getTime(), showInfo2.getTime());
}
});
//showInfoArray will be sorted...
Since you have to use a custom made sorting algorithm and support different ways to sort the data, then you just have to change the way you compare your data. This mean, in your current code, change this part
if (arr[j].time < arr[min].time) {
min = j;
}
To something more generic like
if (compare(arr[j], arr[min]) < 0) {
min = j;
}
Where you only need to change the implementation of the compare method by the one you need. Still, it will be too complex to create and maintain a method that can support different ways to compare the data. So the best option seems to be a Comparator<showInfo>, making your code look like this:
if (showInfoComparator.compare(arr[j], arr[min]) < 0) {
min = j;
}
where the showInfoComparator holds the logic to compare the elements. Now your intSort would become into something more generic:
public static void genericSort(Comparator<showInfo> showInfoComparator) {
//your current implementation with few modifications
//...
//using the comparator to find the minimum element
if (showInfoComparator.compare(arr[j], arr[min]) < 0) {
min = j;
}
//...
//swapping the elements directly in the array instead of swapping part of the data
if (min != i) {
int temp = arr[i].time;
arr[i].time = arr[min].time;
arr[min].time = temp;
}
//...
}
Now, you just have to write a set of Comparator<showInfo> implementations that supports your custom criteria. For example, here's one that compares showInfo instances using the time field:
public class ShowInfoTimeComparator implements Comparator<showInfo> {
#Override
public int compare(showInfo showInfo1, showInfo showInfo2) {
//write the comparison logic
return Integer.compare(showInfo1.getTime(), showInfo2.getTime());
}
}
Another comparator that uses the name field:
public class ShowInfoNameComparator implements Comparator<showInfo> {
#Override
public int compare(showInfo showInfo1, showInfo showInfo2) {
//write the comparison logic
return showInfo1.getName().compareTo(showInfo2.getName());
}
}
Now in your code you can call it like this1:
if (*compare by time*) {
genericSort(showInfoArray, new ShowInfoTimeComparator());
}
if (*compare by name*) {
genericSort(showInfoArray, new ShowInfoNameComparator());
}
if (*another custom rule*) {
genericSort(showInfoArray, new ShowInfoAnotherCustomRuleComparator());
}
where now you can implement a custom rule like compare showInfo objects using two or more fields. Taking as example your name and day fields (as stated in the question):
public class ShowInfoNameAndDayComparator implements Comparator<showInfo> {
#Override
public int compare(showInfo showInfo1, showInfo showInfo2) {
//write the comparison logic
int nameComparisonResult = showInfo1.getName().compareTo(showInfo2.getName());
if (nameComparisonResult == 0) {
return showInfo1.getDay().compareTo(showInfo2.getDay());
}
return nameComparisonResult;
}
}
1: There are other ways to solve this instead using lot of if statements, but looks like that's outside the question scope. If not, edit the question and add it to show another ways to solve this.
Other tips for your current code:
Declare the names of the classes using CamelCase, where the first letter of the class name is Upper Case, so your showInfo class must be renamed to ShowInfo.
To access to the fields of a class, use proper getters and setters instead of marking the fields as public or leaving the with default scope. This mean, your ShowInfo class should become into:
public class ShowInfo {
private String name;
private String day;
private int time;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
//similar for other fields in the class
}
Use selection sort algorithm which is easy to implement,
for (int i = 0; i < arr.length; i++)
{
for (int j = i + 1; j < arr.length; j++)
{
if (arr[i].time > arr[j].time) // Here ur code that which should be compare
{
ShowInfo temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
no need to check min element. go through this wiki http://en.wikipedia.org/wiki/Selection_sort
Why not you use a Collection for this sort of a thingy to work. Moreover, in your added example, you are simply changing one attribute of a given object, while sorting, though you not changing the position of the object as a whole, inside the given list.
Create a List which will contain the references of all the Shows, now compare each attribute of one Show with another, in the List. Once the algorithm feels like, that swapping needs to be done, simply pick the reference from the List, save it in a temp variable, replace it with a new reference at this location, and set duplicate to the one stored in the temp variable. You are done, List is sorted :-)
Here is one small example for the same, for help :
import java.io.*;
import java.util.*;
public class Sorter {
private BufferedReader input;
private List<ShowInfo> showList;
public Sorter() {
showList = new ArrayList<ShowInfo>();
input = new BufferedReader(
new InputStreamReader((System.in)));
}
private void createList() throws IOException {
for (int i = 0; i < 5; i++) {
System.out.format("Enter Show Name :");
String name = input.readLine();
System.out.format("Enter Time of the Show : ");
int time = Integer.parseInt(input.readLine());
ShowInfo show = new ShowInfo(name, time);
showList.add(show);
}
}
private void performTask() {
try {
createList();
} catch (Exception e) {
e.printStackTrace();
}
sortByTime(showList);
}
private void sortByTime(List<ShowInfo> showList) {
int min;
for (int i = 0; i < showList.size(); i++) {
// Assume first element is min
min = i;
for (int j = i+1; j < showList.size(); j++) {
if (showList.get(j).getTime() <
showList.get(min).getTime()) {
min = j;
}
}
if (min != i) {
ShowInfo temp = showList.get(i);
showList.set(i, showList.get(min));
showList.set(min, temp);
}
}
System.out.println("TV Shows by Time");
for(int i = 0; i < showList.size(); i++) {
System.out.println(showList.get(i).getName() +
" - " + showList.get(i).getTime());
}
}
public static void main(String[] args) {
new Sorter().performTask();
}
}
class ShowInfo {
private String name;
int time;
public ShowInfo(String n, int t) {
name = n;
time = t;
}
public String getName() {
return name;
}
public int getTime() {
return time;
}
}
EDIT 2 :
For sorting By Name you can use this function :
private void sortByName(List<ShowInfo> showList) {
int min;
for (int i = 0; i < showList.size(); i++) {
// Assume first element is min
min = i;
for (int j = i+1; j < showList.size(); j++) {
int value = (showList.get(j).getName()).compareToIgnoreCase(
showList.get(min).getName());
if (value < 0)
min = j;
}
if (min != i) {
ShowInfo temp = showList.get(i);
showList.set(i, showList.get(min));
showList.set(min, temp);
}
}
System.out.println("TV Shows by Time");
for(int i = 0; i < showList.size(); i++) {
System.out.println(showList.get(i).getName() +
" - " + showList.get(i).getTime());
}
}
EDIT 3 :
Added Comparable<?> Interface, to the existing class to perform sorting based on specified input. Though one can improve on the logic, by using Enumeration, though leaving it for the OP to try his/her hands on :-)
import java.io.*;
import java.util.*;
public class Sorter {
private BufferedReader input;
private List<ShowInfo> showList;
private int command;
public Sorter() {
showList = new ArrayList<ShowInfo>();
input = new BufferedReader(
new InputStreamReader((System.in)));
command = -1;
}
private void createList() throws IOException {
for (int i = 0; i < 5; i++) {
System.out.format("Enter Show Name :");
String name = input.readLine();
System.out.format("Enter Time of the Show : ");
int time = Integer.parseInt(input.readLine());
ShowInfo show = new ShowInfo(name, time);
showList.add(show);
}
}
private void performTask() {
try {
createList();
} catch (Exception e) {
e.printStackTrace();
}
System.out.format("How would you like to sort : %n");
System.out.format("Press 0 : By Name%n");
System.out.format("Press 1 : By Time%n");
try {
command = Integer.parseInt(input.readLine());
} catch (Exception e) {
e.printStackTrace();
}
sortList(showList);
}
private void sortList(List<ShowInfo> showList) {
int min;
for (int i = 0; i < showList.size(); i++) {
// Assume first element is min
min = i;
for (int j = i+1; j < showList.size(); j++) {
showList.get(j).setValues(command);
int value = showList.get(j).compareTo(showList.get(min));
if (value < 0) {
min = j;
}
}
if (min != i) {
Collections.swap(showList, i, min);
}
}
System.out.println("TV Shows by Time");
for(int i = 0; i < showList.size(); i++) {
System.out.println(showList.get(i).getName() +
" - " + showList.get(i).getTime());
}
}
public static void main(String[] args) {
new Sorter().performTask();
}
}
class ShowInfo implements Comparable<ShowInfo> {
private String name;
private int time;
private int command;
public ShowInfo(String n, int t) {
name = n;
time = t;
}
public String getName() {
return name;
}
public int getTime() {
return time;
}
public void setValues(int cmd) {
command = cmd;
}
public int compareTo(ShowInfo show) {
int lastCmp = 1;
if (command == 0) {
lastCmp = name.compareTo(show.name);
} else if (command == 1) {
if (time < show.time) {
lastCmp = -1;
} else if (time == show.time) {
lastCmp = 0;
} else if (time > show.time) {
lastCmp = 1;
}
}
return lastCmp;
}
}
I am stuck on this part where it does not write to an output file
the first class is contact I had to modify this is not my class is the authors class
I just had to use it
//********************************************************************
// Contact.java Author: Lewis/Loftus
//
// Represents a phone contact.
//********************************************************************
public class Contact implements Comparable
{
private String firstName, lastName, phone;
//-----------------------------------------------------------------
// Constructor: Sets up this contact with the specified data.
//-----------------------------------------------------------------
public Contact (String first, String last, String telephone)
{
firstName = first;
lastName = last;
phone = telephone;
}
//-----------------------------------------------------------------
// Returns a description of this contact as a string.
//-----------------------------------------------------------------
public String toString ()
{
return lastName + ", " + firstName + "\t" + phone;
}
//-----------------------------------------------------------------
// Returns true if the first and last names of this contact match
// those of the parameter.
//-----------------------------------------------------------------
public boolean equals (Object other)
{
return (lastName.equals(((Contact)other).getLastName()) &&
firstName.equals(((Contact)other).getFirstName()));
}
//-----------------------------------------------------------------
// Uses both last and first names to determine ordering.
//-----------------------------------------------------------------
public int compareTo (Object other)
{
int result;
String otherFirst = ((Contact)other).getFirstName();
String otherLast = ((Contact)other).getLastName();
if (lastName.equals(otherLast))
result = firstName.compareTo(otherFirst);
else
result = lastName.compareTo(otherLast);
return result;
}
//-----------------------------------------------------------------
// First name accessor.
//-----------------------------------------------------------------
public String getFirstName ()
{
return firstName;
}
//-----------------------------------------------------------------
// Last name accessor.
//-----------------------------------------------------------------
public String getLastName ()
{
return lastName;
}
}
this class oes the sorting this is fine. it does the sorting no prblem
public class Sorting {
public static void bubbleSortRecursive(Comparable[] data, int n)
{
if (n < 2)
{
return;
}
else
{
int lastIndex = n - 1;
for (int i = 0; i < lastIndex; i++)
{
if (data[i].compareTo(data[i + 1]) > 0)
{ //swap check
Comparable tmp = data[i];
data[i] = data[i + 1];
data[i + 1] = tmp;
}
}
bubbleSortRecursive(data, lastIndex);
}
}
public static void selectionSortRecursive(Comparable[] data, int n)
{
if (n < 2)
{
return;
}
else
{
int lastIndex = n - 1;
int largestIndex = lastIndex;
for (int i = 0; i < lastIndex; i++)
{
if (data[i].compareTo(data[largestIndex]) > 0)
{
largestIndex = i;
}
}
if (largestIndex != lastIndex)
{ //swap check
Comparable tmp = data[lastIndex];
data[lastIndex] = data[largestIndex];
data[largestIndex] = tmp;
}
selectionSortRecursive(data, n - 1);
}
}
}
this is the part I need help with. It is not outputing to he p4output.txt, i dont know what the problem is.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class TestProject4 {
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
doSelectionSortRecursive();
}
private static void doBubbleSortRecursive()
{
Contact[] contacts = createContacts();
System.out.println("Before bubbleSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
Sorting.bubbleSortRecursive(contacts, contacts.length);
System.out.println("\nAfter bubbleSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
}
private static void doSelectionSortRecursive()
{
Contact[] contacts = createContacts();
System.out.println("Before selectionSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
Sorting.selectionSortRecursive(contacts, contacts.length);
System.out.println("\nAfter selectionSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
}
private static void printContacts(Contact[] contacts)
{
try
{
// this part I need help with it is not outputing in the text file
File file = new File("p4output.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (Contact contact : contacts)
{
bw.write(contact.toString());
}
bw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("\t" + contacts);
}
public static Contact[] createContacts()
{
return new Contact[]
{
new Contact("John" , "Smith" , "610-555-7384"),
new Contact("Sarah" , "Barnes" , "215-555-3827"),
new Contact("Mark" , "Riley", "333-333-3333"),
new Contact("Laura" , "Getz" ,"663-555-3984"),
new Contact("Larry" , "Smith" , "464-555-3489"),
new Contact("Frank" , "Phelps" , "322-555-2284"),
new Contact("Mario" , "Guzman" , "804-555-9066"),
new Contact("Marsha" , "Grant" , "243-555-2837"),
};
}
}
According to Eclipse, you never call/use printContacts(Contact[] contacts); method
Your printContacts(Contact[] contacts); contains the statements to write a file.
You don't appear to call the function printContacts() in your program. Try calling it after you do your contact creation and sorting.
It might look like this:
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
doSelectionSortRecursive();
printContacts(contactArray);//inserted code
}
Also, when you call your sorting methods, doSelectionSortRecursive(), you don't return the list of contacts. Make a return statement for it and then put the contact array into your printContacts function.
Here's an example:
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
Contact[] contacts = doSelectionSortRecursive();
printContacts(contacts);
}
public static Contact[] doSelectionSortRecursive(){
Contact[] contacts = createContacts();
//your sorting code
return contacts;
}
Using this method allows you to get the array of contacts from the method once it has been sorted.