Compare Integer, arrays of class instances - java

Ok so I'm kind of in the loss here but here goes. So I need to sort the array medalList when they get printed out. First I need to sort by gold medals which are added to the index [0], second after silvers in index [1], third after bronze in index [2] and last if a team is tied they get sorted by team name. Do I need to call a sorting method in another class, keep track of one and sort through and compare to the rest of the teams and if they're the best print them out first?
How do I compare Integers in an array of one classes to another?
When a user enters a certain command a list of teams with their results will get printed out.
As of now it looks like this:
1st 2nd 3rd Team Name
0 0 0 North Korea
3 1 1 America
5 0 2 France
2 1 3 Germany
I want it to say:
1st 2nd 3rd Team Name
5 0 2 France
3 1 1 America
2 1 3 Germany
0 0 0 North Korea
import java.util.ArrayList;
import java.util.Arrays;
public class Team {
private String teamName;
private ArrayList<Participant> participantList = new ArrayList<Participant>();
private int[] medalList = new int[3];
public Team(String teamName) {
this.teamName = teamName;
}
public String getTeamName() {
return teamName;
}
public void addParticipant(Participant participant) {
participantList.add(participant);
}
public void removeFromTeam(int participantNr){
for(int i = 0; i < participantList.size(); i++){
if(participantList.get(i).getParticipantNr() == participantNr){
participantList.remove(i);
}
}
}
public void printOutParticipant() {
for(int i = 0; i < participantList.size(); i++){
System.out.println(participantList.get(i).getName() + " " + participantList.get(i).getLastName());
}
}
public boolean isEmpty() {
boolean empty = false;
if (participantList.size() == 0) {
empty = true;
return empty;
}
return empty;
}
public void emptyMedalList(){
Arrays.fill(medalList, 0);
}
public void recieveMedals(int medal) {
if(medal == 1){
int gold = 0;
gold = medalList[0];
medalList[0] = ++gold;
} else if (medal == 2){
int silver = 0;
silver = medalList[1];
medalList[1] = ++silver;
} else if (medal == 3){
int bronze = 0;
bronze = medalList[2];
medalList[2] = ++bronze;
}
}
public void printMedals(){
System.out.println(medalList[0] + " " + medalList[1] + " " + medalList[2] + " " + teamName);
}
public int compareTo(Team team) {
int goldDif = Integer.compare(team.medalList[0], this.medalList[0]);
if (goldDif != 0)
return goldDif;
int silverDif = Integer.compare(team.medalList[1], this.medalList[1]);
if (silverDif != 0)
return silverDif;
int bronzeDif = Integer.compare(team.medalList[2], this.medalList[2]);
if (bronzeDif != 0)
return bronzeDif;
return this.getTeamName().compareTo(team.getTeamName());
}
public String toString() {
return teamName;
}
}

Make your Team class comparable
public class Team implements Comparable<Team> {
and add a comparison method
#Override
public int compareTo(final Team other) {
for (int i = 0; i < 3; i++) {
final int compareMedals = Integer.compare(medalList[i], other.medalList[i])
if (compareMedals != 0) {
return compareMedals;
}
}
return teamName.compareTo(other.teamName);
}
This will check gold medals first, then silver medals if the amount of gold medals is equal and so on and use the team name comparison as a last resort. You can then sort a collection of Teams with
final List<Team> teams = new ArrayList<>();
...
Collections.sort(teams);
EDIT:
Or if you like it in Java 8 style you could also write your comparison method like
#Override
public int compareTo(final Team other) {
return Stream.of(0, 1, 2)
.map(i -> Integer.compare(medalList[i], other.medalList[i]))
.filter(i -> i != 0)
.findFirst()
.orElse(teamName.compareTo(other.teamName));
}

Related

How to create a 'best fit' comparison of several integers and an input integer in Java?

I have 3 (subject to change to more rooms in the future, but that's irrelevant) rooms, all with a different number of seats (suppose these are 'Room' Objects):
Room
Seats
1
10
2
20
3
30
I then input a value of the number of seats I need to reserve and then my code will automatically assign the user a room based on their input with the room that has the "best fit" or closest amount capable of seats that best fits their demand. So some examples
User inputs:
My Code Assigns them Room:
10
1
22
3
25
3
4
1
9
1
15
2
(Assume the inputs won't go over 30) If the inputs go over 30 I do something else, which isn't relevant to this question.
So here's my attempt:
returnValue = 0;
inputValue = 10; //can be anything, doesn't have to be 10
ArrayList<Room> rooms= new ArrayList<Room>(); //where each room is already in the array list identified by it's unique number
//assume getRoomNumber() returns the room number of the Room object
// assume getRoomSeats() returns the number of seats of a Room object
for (Room i: rooms){
if (i.getRoomSeats()==inputValue){
returnValue = i.getRoomNumber();
}
elif(i.getRoomSeats()<inputValue){//donothing}
elif(i.getRoomSeats()>inputValue){
returnValue = i.getRoomNumber;
}}}
Is this the best way to do what I want?
You can do something like this
import java.util.ArrayList;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
new Main().test();
}
void test() {
int inputValue = 22;
ArrayList<Room> rooms = new ArrayList<Room>(); // where each room is already in the array list identified by
rooms.add(new Room(10, 1));
rooms.add(new Room(20, 2));
rooms.add(new Room(30, 3));
Integer currentDifference = null;
Room roomWithMinimalDifference = null;
for (Room room : rooms) {
int difference = room.getRoomSeats() - inputValue;
System.out.println("room "+room.getRoomNumber()+" difference "+difference);
boolean roomFitsEnteredSeats = difference >= 0; //check if room fits the entered value
if(roomFitsEnteredSeats) {
if (currentDifference == null || difference < currentDifference) {
currentDifference = difference;
roomWithMinimalDifference = room;
}
}
}
if (roomWithMinimalDifference != null) {
System.out.println("found room" + roomWithMinimalDifference.getRoomNumber() + " seats "
+ roomWithMinimalDifference.roomSeats);
} else {
System.out.println("no room was found");
}
System.out.println("-----------------------");
//========== or use this with java >= 8
Room bestMatchingRoom = rooms.stream()
.sorted(Comparator.comparingInt(Room::getRoomSeats))
.filter(r -> r.getRoomSeats() >= inputValue)
.findFirst()
.orElse(null);
if (bestMatchingRoom != null) {
System.out.println("found room" + roomWithMinimalDifference.getRoomNumber() + " seats "
+ roomWithMinimalDifference.roomSeats);
} else {
System.out.println("no room was found");
}
}
class Room {
int roomSeats;
int roomNumber;
public Room(int roomSeats, int roomNumber) {
super();
this.roomSeats = roomSeats;
this.roomNumber = roomNumber;
}
public int getRoomSeats() {
return roomSeats;
}
public void setRoomSeats(int roomSeats) {
this.roomSeats = roomSeats;
}
public int getRoomNumber() {
return roomNumber;
}
public void setRoomNumber(int roomNumber) {
this.roomNumber = roomNumber;
}
}
}

Count even,odd and perfect number for arrays java? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Question:
Write a Number class that can be used to determine if a number is odd, even, or
perfect. Then, use this Number class to determine how many numbers in the list are odd, even, and perfect.
Number Class:
public class Number
{
private Integer number;
public Number(int n)
{
number=n;
}
public boolean isEven()
{
if(number % 2 == 0)
return true;
else
return false;
}
public boolean isOdd()
{
if(number % 2 != 0)
return true;
else
return false;
}
public boolean isPerfect()
{
int count = 0;
for(int i = 1; i<number; i++)
{
if(number % i == 0)
count += i;
}
if(number == count)
{
return true;
}
else
return false;
}
public String toString()
{
return "" +number;
}
}
My number class is running good there is no problem in my Number class. But in my number analyzer class where i find the number of odd,even and perfect.
Number Analyzer class:
public class NumberAnalyzer
{
private ArrayList<Number> list;
public NumberAnalyzer(int l)
{
list=l;
}
public int countOdds()
{
int odd = 0;
for(int i=0; i<list.size(); i++)
{
if(list.isOdd() == true)
return odd++;
}
}
public int countEvens()
{
int even = 0;
for(int x = 0; x<list.size(); x++)
{
if(list.isEven() == true)
return even++;
}
}
public int countPerfects()
{
int perfect = 0;
for(int z = 0; z<list.size(); z++)
{
if(list.isPerfect() == true)
return perfect++;
}
}
public String toString()
{
return "" + list;
}
}
Please make correction on this class so my program run perfectly. I do not understand the problem please make change in this so program work perfectly.
Runner of program:
import static java.lang.System.*;
public class Runner
{
public static void main( String args[] )
{
int[] r = {5, 12, 9, 6, 1, 4, 8, 6 };
NumberAnalyzer test = new NumberAnalyzer(r);
out.println(test);
out.println("odd count = "+test.countOdds());
out.println("even count = "+test.countEvens());
out.println("perfect count = "+test.countPerfects()+"\n\n\n");
}
}
Correct answers with this Runner:
[5, 12, 9, 6, 1, 4, 8, 6]
odd count = 3
even count = 5
perfect count = 2
Thank you
I didn't understand how it could work if it even didn't complile but nevermind. You need to change 2 classes: NumberAnalyzer and Runner. Please have a look:
public class Runner {
public static void main(String args[]) {
Number[] r = {new Number(5), new Number(12), new Number(9), new Number(6),
new Number(1), new Number(4), new Number(8), new Number(6)};
NumberAnalyzer test = new NumberAnalyzer(r);
out.println(test);
out.println("odd count = " + test.countOdds());
out.println("even count = " + test.countEvens());
out.println("perfect count = " + test.countPerfects() + "\n\n\n");
}
}
and
import java.util.Arrays;
import java.util.List;
public class NumberAnalyzer {
private List<Number> list;
public NumberAnalyzer(Number[] l) {
list = Arrays.asList(l);
}
public int countOdds() {
int odd = 0;
for (Number value : list) {
if (value.isOdd() == true) {
odd++;
}
}
return odd;
}
public int countEvens() {
int even = 0;
for (Number value : list) {
if (value.isEven() == true) {
even++;
}
}
return even;
}
public int countPerfects() {
int perfect = 0;
for (Number value : list) {
if (value.isPerfect() == true) {
perfect++;
}
}
return perfect;
}
public String toString() {
return "" + list;
}
}
in that case it returns a correct output.
Your approach for resolving this problem has a lot of problems, especially in NumberAnalyzer class.
1) You should call the isOdd(), isEven() etc. on an element of the list, not on the list itself -> list.get(i).isEven()
2) The return even++ will exit the loop and return 1 if the condition is met, and the method is not even working since you don't have a return statement in case if the if statement from the for loop doesn't get executed.
3) Not a big problem, but the x and z can be declared as i too -> more intuitive ( i ndex)
4) The isPerfect() method is not correct, an easy solution to solve this problem could be using Math.sqrt() and Math.floor()
5) You're trying to pass an int[] array and the constructor expect an int. And after this, you have an ArrayList<Number> inside the NumberAnalyzer class and you're trying to assign to this list an int value.
Solutions:
1) + 2) + 3) :
public class NumberAnalyzer {
private List<Number> list; //Changed the ArrayList<> to List<>
public NumberAnalyzer(List<Number> l) {
list = l;
}
public int countOdds() {
int odd = 0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).isOdd())
odd++;
}
return odd;
} // SAME FOR THE OTHER METHODS.
}
4)
public boolean isPerfect()
{
int square = Math.sqrt(number);
return (square - Math.floor(square)) == 0;
}
5) The static void main method should now look like this:
Integer[] r = {5, 12, 9, 6, 1, 4, 8, 6};
List<Integer> rList = Arrays.asList(r);
List<Number> numberList = rList.stream().map(Number::new).collect(Collectors.toList());
NumberAnalyzer test = new NumberAnalyzer(numberList);

Find duplicate values in input

I have an input like:
Apple: 0 1
Apple: 4 5
Pear: 0 10
Pear: 11 13
Apple: 5 10
Apple: 2 4
And I'm looking for rows, where the fruits are the same and the first value equals to another row's second vale. So I'm looking for rows like: Apple: 4 5 Apple: 2 4 and I will also need Apple: 4 5 Apple: 5 10
On the otherhand, I don't want to search the whole data. I mean I don't want to search for Apple in Pears.
Should I use HashMap? or HashSet? or something else?
Thanks for replies.
Give this a try... It utilizes a HashMap of Lists
public static void main(String[] args) {
List<String> inputs = new ArrayList<>();
inputs.add("Apple: 0 1");
inputs.add("Apple: 4 5");
inputs.add("Pear: 0 10");
inputs.add("Pear: 11 13");
inputs.add("Apple: 5 10");
inputs.add("Apple: 2 4");
Map<String, List<Fruit>> fruits = new HashMap<>();
for (String input : inputs) {
String[] inputPieces = input.split(" ");
String name = inputPieces[0].replace(":", "");
int first = Integer.parseInt(inputPieces[1]);
int second = Integer.parseInt(inputPieces[2]);
if (!fruits.containsKey(name)) {
fruits.put(name, new ArrayList<Fruit>());
}
fruits.get(name).add(new Fruit(name, first, second));
}
for (String key : fruits.keySet()) {
System.out.println(key + ": " + findDuplicates(fruits.get(key)));
}
}
private static List<Fruit> findDuplicates(List<Fruit> fruits) {
List<Fruit> results = new ArrayList<>();
for (int i = 0; i < fruits.size(); i++) {
for (int j = 0; j < fruits.size(); j++) {
if (j == i) {
continue;
}
if ((fruits.get(i).first == fruits.get(j).second) ||
(fruits.get(j).first == fruits.get(i).second)) {
if (!results.contains(fruits.get(i))){
results.add(fruits.get(i));
}
}
}
}
return results;
}
public static class Fruit {
private String name;
private int first;
private int second;
public Fruit(String name, int first, int second) {
this.name = name;
this.first = first;
this.second = second;
}
#Override
public String toString() {
return String.format("%s: %d %d", name, first, second);
}
}
Results:

Insert object element into array in ordered position, without using sort algorithm in Java

I have programming projectת I have it almost finished, but I am struggling on inserting a new object made from the console into the array at the correct position.
I can make the object, insert at either the beginning or end, delete object, etc. but the array needs to be in order (month, day, time) and I am stuck.
I have been searching for a good day and a half, through forums, info websites, books, etc. and cannot find an answer.
P.S. I am NOT allowed to use anything other than an array (ArrayList, LinkedList, etc), and i cannot use any sorting algorithms (bubblesort, insertionsort, etc.)
Directions call specifically for me to shift array elements as needed and put new object in between/at correct position. Also I am using NetBeans.
/*
*
*
*/
package project1;
import UserInput.UserInput;
public class Schedule {
Delivery[] deliObj = new Delivery[20];
int count = 0;
public Schedule(){//set default objects
deliObj[0] = new Delivery("MAR", 4, 17, 30, "Pizza");
count++;
deliObj[1] = new Delivery("APR", 1, 06, 30, "Special Deliery");
count++;
deliObj[2] = new Delivery("MAY", 6, 12, 00, "Amazon (Books)");
count++;
deliObj[3] = new Delivery("JUN", 3, 11, 15, "Car Parts");
count++;
}
public void setDelivery(Delivery[] deliObj){
this.deliObj = deliObj;
}
public Delivery[] getDelivery(){
return this.deliObj;
}
public static void main(String[] args){
Schedule scheduleObj = new Schedule();
scheduleObj.run();
}
public void run(){
System.out.println("\n***** MAIN DELIVERY CONSOLE *****\n");
System.out.println("A)dd delivery");
System.out.println("D)delete Delivery");
System.out.println("L)ist Delivery");
System.out.println("E)xit");
char selection = Character.toUpperCase(UserInput.getChar());
switch(selection){
case 'A': addDelivery();
break;
case 'D': deleteDelivery();
break;
case 'L': listDelivery();
break;
case 'E': System.exit(0);
}
}
public void addDelivery(){
Delivery getInputDelivery = new Delivery();
getInputDelivery.InputDelivery();
deliObj[count] = getInputDelivery;
count++;
insertDelivery(getInputDelivery);
run();
}
public void deleteDelivery(){
System.out.println("Please enter the number you wish to delete: ");
int num = UserInput.getInt(0,count);
//deliObj[num-1] = new Delivery();
deliObj[num-1] = null;
count--;
run();
}
public void listDelivery(){
for(int i=0;i<count;i++) {
System.out.println(i+1 + ". " + deliObj[i]);
}
run();
}
public boolean compareDelivery(Delivery A1, Delivery A2){
//Delivery delivery = deliObj[count-4];
int numMonth;
int numMonth1;
numMonth = Delivery.integerMonth(A1.getMonth());
numMonth1 = Delivery.integerMonth(A2.getMonth());
if(numMonth < numMonth1){
return true;
}
else if(numMonth == numMonth1){
if(A1.getDay() < A2.getDay()){
return true;
}
else if(A1.getDay() == A2.getDay()){
if(A1.getHour() < A2.getHour()){
return true;
}
else if(A1.getHour() == A2.getHour()){
if(A1.getMintute() < A2.getMintute()){
return true;
}
}
}
} //else return false;
return false;
}
public void insertDelivery(Delivery temp){
for(int i = 0; i < count; i++){
/*if(!compareDelivery(deliObj[i], temp)) {
for(int k = 1; k < count; k++) {
Delivery temp2 = deliObj[k];
deliObj[k] = deliObj[count-1];
deliObj[count-1] = temp2;
}*/
if(compareDelivery(deliObj[i], temp)) {
Delivery temp2 = deliObj[i];
deliObj[i] = deliObj[count-1];
deliObj[count-1] = temp2;
}
}
/*for (int k = 0; k < count-1; k++) {
if(compareDelivery(deliObj[k], temp)) {
Delivery temp2 = deliObj[k];
deliObj[k] = deliObj[count-1];
deliObj[count-1] = temp2;
//deliObj[count] = deliObj[k];
//deliObj[k] = deliObj[count-1];
}
} */
}
}
this is my main class where things are run, but here is the other subclass that has the constructors and getters/setters etc.
package project1;
import UserInput.UserInput;
public class Delivery {
private static final String FINAL_MONTH[] = {"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};
private String month;
private int day;
private int hour;
private int minute;
private int second;
private String userMessage;
public static int integerMonth(String compareMonth){
for(int i = 0; i < FINAL_MONTH.length; i++){
if(compareMonth.equals(FINAL_MONTH[i])){
return i;
}
}
return -1;
}
public Delivery(String month, int day, int hour, int minute, String userMessage) {
this.month = month;
this.day = day;
this.hour = hour;
this.minute = minute;
this.userMessage = userMessage;
}
public void setMonth(String month) {
for (String FINAL_MONTH1 : FINAL_MONTH) {
if (month.equalsIgnoreCase(FINAL_MONTH1)) {
this.month = month.toUpperCase();
}
}
}
public String getMonth() {
return this.month;
}
public void setDay(int day) {
this.day = day;
}
public int getDay() {
return this.day;
}
public void setHour(int hour) {
this.hour = hour;
}
public int getHour() {
return this.hour;
}
public void setMinute(int minute) {
this.minute = minute;
}
public int getMintute() {
return this.minute;
}
public void setSecond(int second) {
this.second = second;
}
public int getSecond() {
return this.second;
}
public void setUserMessage(String userMessage) {
this.userMessage = userMessage;
}
public String getUserMessage() {
return this.userMessage;
}
public Delivery() {
month = "JAN";
day = 1;
hour = 12;
minute = 00;
userMessage = "default";
}
#Override
public String toString() {
String data = String.format(month + " %02d, " + "%02d:" + "%02d " + userMessage, day, hour, minute);
return data;
}
public void InputDelivery() {
System.out.println("Enter month of delivery(3 letter abbreviation): ");
setMonth(UserInput.getString(3, 3));
System.out.println("Enter day of delivery: ");
setDay(UserInput.getInt(0, 31));
System.out.println("Enter hour of delivery (0-23): ");
setHour(UserInput.getInt(0, 24));
System.out.println("Enter minute of delivery (0-59): ");
setMinute(UserInput.getInt(0, 59));
System.out.println("Enter message for delivery (40 Character Max): ");
setUserMessage(UserInput.getString(0,40));
System.out.println(toString());
}
}
I really need help with just the insertDelivery() method, if you see other errors you can mention them but please try to just advise me on that portion!
I'll start by assuming that "anything other than an array" does not extend to utility classes such as java.util.Arrays. If it does, you will need to implement some the method I use below your self.
The first step is to either make your Delivery implement Comparable<Delivery> or make a new class that implements Comparator<Delivery>. This defines an ordering for your Delivery object. This change should be simple because you have already defined a compareDelivery method.
With this modification made, you can get the index of at which to insert the value by calling Arrays.binarySearch(deliObj,temp). If you aren't allowed to use the Arrays class, this link show a simple binary search implementation.
1 int[] data;
2 int size;
3
4 public boolean binarySearch(int key)
5 {
6 int low = 0;
7 int high = size - 1;
8
9 while(high >= low) {
10 int middle = (low + high) / 2;
11 if(data[middle] == key) {
12 return true;
13 }
14 if(data[middle] < key) {
15 low = middle + 1;
16 }
17 if(data[middle] > key) {
18 high = middle - 1;
19 }
20 }
21 return false;
22 }
Having this index, you now need to insert your object at this point. Using arrays however, this is slightly more difficult than it seems. The length of an Array is immutable, so you have to create a new Array that is one element longer than your current array before inserting the object. You'll be doing what happens behind the scenes in ArrayList, more or less.Inserting an element into an array has been covered on StackOverflow before, so I'll just refer you to a helpful answer.
public static int[] addPos(int[] a, int pos, int num) {
int[] result = new int[a.length];
for(int i = 0; i < pos; i++)
result[i] = a[i];
result[pos] = num;
for(int i = pos + 1; i < a.length; i++)
result[i] = a[i - 1];
return result;
}
In general you cannot insert an element into an array. Arrays are fixed length (they contain exactly n elements and you cannot alter an array to contain n+1 or n-1 elements). What you can do is create a new array that has space for n+1elements and copy the elements from the original array into the new array inserting the new element in the correct place as you create it. You can also create it to be too large in anticipation of getting more elements (looks like what you have done) and then start to shift the elements up.
This sounds like a homework question. Are you able to ask a someone (a lab helper, tutor, co-student) if you have the right idea? The requirements "I am NOT allowed to use anything other than an array" and the need to insert seem at odds.

CompareTo bubble sort

I am attempting to sort the values in my program using the Bubble Sort method. I believe that my code in the organisedRoom method is correct. However when I run the code, add some customers and then attempt to sort them, the program crashes. If anyone can please point me in the right direction I would greatly appreciate it.
package test;
import java.io.IOException;
import java.util.Scanner;
public class Test {
private class Customer implements Comparable<Customer>{
private String name;
public Customer(String name) {
this.name = name;
}
//Override to stop the program returning memory address as string
#Override
public String toString() {
return name;
}
#Override
public int compareTo(Customer c) {
return name.compareTo(c.name);
}
}
//Array to store customers
public Customer[] customers;
public Scanner input = new Scanner(System.in);
public Test(int nRooms) throws IOException {
customers = new Test.Customer[nRooms];
System.out.println("Welcome to the Summer Tropic Hotel\n");
chooseOption();
}
final JFileChooser fc = new JFileChooser();
// Call new Hotel with int value to allocate array spaces
public static void main(String[] args) throws IOException {
Test t = new Test(11);
}
// New procedure to return User input and point to next correct method
private String chooseOption() throws IOException {
// Set to null, this will take user input
String choice;
//Menu options
System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
System.out.println("A: " + "This will add a new entry\n");
System.out.println("O: " + "View booked rooms, in order of customers name.\n");
System.out.println("X: " + "Exit the program\n");
// Take user input and assign it to choice
choice = input.next();
// Switch case used to return appropriate method
switch (choice.toUpperCase()) {
case "A" :
System.out.println("");
addCustomer();
return this.chooseOption();
case "O" :
System.out.println("");
organisedRoom();
return this.chooseOption();
case "X":
System.exit(0);
}
return choice;
}
// Add a new customer to the Array
public void addCustomer() throws IOException {
// New variable roomNum
int roomNum = 1;
// Loop
do {
// Take user input as room number matching to array index - 1
System.out.println("Please choose a room from 1 to 10");
roomNum = input.nextInt() - 1;
// If room is already booked print this
if (customers[roomNum] != null) {
System.out.println("Room " + roomNum + 1 + " is not free, choose a different one.\n");
this.addCustomer();
}
// Do until array index does not equal to null
} while (customers[roomNum]!= null);
System.out.println("");
// User input added to array as name replacing null (non case-sensetive)
System.out.println("Now enter a name");
customers[roomNum] = new Customer(input.next().toLowerCase());
// Customer (name) added to room (number)
System.out.println(String.format("Customer %s added to room %d\n", customers[roomNum], roomNum + 1));
}
private void organisedRoom() {
boolean flag = true;
Customer temp;
int j;
while (flag) {
flag = false;
for (j = 0; j < customers.length - 1; j++) {
if (customers[j].compareTo(customers[j+1]) < 0) {
temp = customers[j];
customers[j] = customers[j + 1];
customers[j + 1] = temp;
flag = true;
}
}
}
}
}
I think this is because the initialisation of the array adds null to all the array index places.
The stack trace is as follows:
Exception in thread "main" java.lang.NullPointerException
at test.Test$Customer.compareTo(Test.java:34)
at test.Test.organisedRoom(Test.java:133)
at test.Test.chooseOption(Test.java:83)
at test.Test.chooseOption(Test.java:79)
at test.Test.chooseOption(Test.java:79)
at test.Test.<init>(Test.java:46)
at test.Test.main(Test.java:55)
Java Result: 1
It fails because you create Customer[] which will be initialized with11 null references. If you want to order them all elements in the array will be compared. Which lead into the java.lang.NullPointerException.
Store the Customer in an ArrayList. Then you should be able to prevent this error.
edit
If you really need to stick as close as possible to your current code. The following would fix your sorting. (don't use this solution for a real life project)
private void organisedRoom() {
for (int i = customers.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (customers[j + 1] == null) {
continue;
}
if (customers[j] == null ||customers[j + 1].compareTo(customers[j]) < 0) {
Customer temp = customers[j + 1];
customers[j + 1] = customers[j];
customers[j] = temp;
}
}
}
System.out.println("show rooms: " + Arrays.toString(customers));
}
edit 2
To keep most of your current code, you might store the room in the Customer instance (which I personally would not prefer).
// change the constructor of Customer
public Customer(String name, int room) {
this.name = name;
this.room = room;
}
// change the toString() of Customer
public String toString() {
return String.format("customer: %s room: %d", name, room);
}
// store the Customer like
customers[roomNum] = new Customer(input.next().toLowerCase(), roomNum);
Your implementation of Bubble Sort is incorrect. It uses nested for loops.
for(int i = 0; i < customers.length; i++)
{
for(int j = 1; j < (customers.length - i); j++)
{
if (customers[j-1] > customers[j])
{
temp = customers[j-1];
customers[j-1] = customers[j];
customers[j] = temp;
}
}
}

Categories

Resources