Java indexOfMaxInRange [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am doing a project for my Java class and I can't figure out how to find the index of the max time and I need help to get this method working.
public class ReservationList {
Reservations[] reservationsArray;
String name, phone, time;
int index, numberInAParty;
public ReservationList(int size) {
reservationsArray = new Reservations[size];
}
//Adds items to the reservations array
public void addArrayItem(int index, Reservations reservation) {
this.reservationsArray[index] = reservation;
}
//Finds the index of the highest number
public static int indexOfMaxInRange (ReservationList list, int low, int high) {
int timeZero = Integer.valueOf(list.reservationsArray[0].time.replace(":", ""));
int max = timeZero;
int maxIndex = 0;
for (int i = low; i < high; i++) {
int time = Integer.valueOf(list.reservationsArray[i].time.replace(":", ""));
if (time > max) {
System.out.println("Pass");
maxIndex = i;
//max = Integer.valueOf(list.reservationsArray[i].time);
}
}
return maxIndex;
}
//Swaps array elements
private static void swapElement (ReservationList list, int indexOne, int indexTwo) {
Reservations temp = list.reservationsArray[indexOne];
list.reservationsArray[indexOne]= list.reservationsArray[indexTwo];
list.reservationsArray[indexTwo]= temp;
}
//Sorts through the array
protected static void sortArray(ReservationList list) {
for(int i = list.reservationsArray.length;i >= 0; i--){
int big = indexOfMaxInRange(list,0,i);
swapElement(list, big,i);
}
for(int i=list.reservationsArray.length;i>0;i=i-1){
swapElement(list,i,i-1);
}
}
}
public class Reservations {
protected String name;
protected String phone;
protected int numberInAParty;
protected String time;
public Reservations() {
this.name = "";
this.phone = "";
this.time = "";
this.numberInAParty = 0;
}
public Reservations(String name, String phone, String time, int numberInAParty, int size) {
this.name = name;
this.phone = phone;
this.time = time;
this.numberInAParty = numberInAParty;
}
public void printReservation (Reservations x) {
System.out.println("Name: " + x.name);
System.out.println("Phone number: " + x.phone);
System.out.println("Time: " + x.time);
System.out.println("Party number: " + x.numberInAParty);
}
}
Here is how the list is initialized
private void loadArray (String fileName, ReservationList list) throws IOException, FileNotFoundException {
BufferedReader reader = new BufferedReader (new InputStreamReader(new FileInputStream(fileName)));
Reservations temp = new Reservations();
String reservation;
int i = 0;
String delimiters = "[ ]+";
try {
while ((reservation = reader.readLine()) !=null) {
String[] splitReservation = reservation.split(delimiters);
temp.name = splitReservation[0];
temp.phone = splitReservation[1];
temp.numberInAParty = Integer.valueOf((String)splitReservation[2]);
temp.time = splitReservation[3];
list.addArrayItem(i, temp);
list.sortArray(list);
ReservationsTextArea.append(list.reservationsArray[i].name + " " + list.reservationsArray[i].phone + " " + list.reservationsArray[i].numberInAParty + " " + list.reservationsArray[i].time + "\n");
i++;
}
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
}
Let me know if you need more of the code. This is my first time posting so let me know if I did anything wrong.
I am inputting an object that contains a name, phone number, party amount, and time. This method is supposed to sort the times so that the smallest time is first and latest time is last.
I get a nullpointerexception after it prints out pass, it is just there for debugging purposes. It works if I replace max with 0 however and I don't understand why. Let me know if you need anything more.
I didn't create some of these methods so don't criticize any of it please. All I want it to fix what is specified. Sorry that it is ridiculously long. Our group used the swing editor in NetBeans to make it to save time, please don't comment about how Im not gonna learn anything etc. I know.
The method that adds the objects are loadArray and DisplayAllButtonActionPerformed calls that method
I'm also aware that sortArray is in a loop and until it works I am just keeping it there.

Change your loadArray code so that a new Temp Object is created in each iteration of the loop
while ((reservation = reader.readLine()) !=null) {
Reservations temp = new Reservations();
temp.name = splitReservation[0];
// etc
otherwise you are always working on the same Object

I haven't been able to narrow down the NullPointerException, so you may want to debug the file that you are reading in and check the array after reading in all your data.
The problems I did find so far, though, are that the sortArray is wrong. You initialize i = list.length, which would throw an IndexOutOfBoundException. You also have the same for-loop twice for some reason.
So here is the fix for that (which I verified sorts ascending).
protected static void sortArray(ReservationList list) {
for (int i = list.reservationsArray.length - 1; i >= 0; i--) {
int big = indexOfMaxInRange(list, 0, i);
swapElement(list, big, i);
}
}
As for the max index method. There has to be somewhere you are getting a null object in order for you to get that error. From my simple testing, this works for me.
public static int indexOfMaxInRange(ReservationList list, int low, int high) {
int max = Integer.MIN_VALUE; // Set this to be the lowest possible integer
int maxIndex = low;
for (int i = low; i < high; i++) {
String timestamp = list.reservationsArray[i].time.replace(":", "");
int time = Integer.valueOf(timestamp);
if (time > max) {
maxIndex = i;
max = time;
}
}
return maxIndex; // note if low >= high, low is returned
}
You also don't need to sort the array every single time you add a Reservations object, so do something like
try {
while ((reservation = reader.readLine()) != null) {
String[] splitReservation = reservation.split("\\s+"); // this is the proper delimiter you want
Reservations temp = new Reservations();
temp.name = splitReservation[0];
temp.phone = splitReservation[1];
temp.numberInAParty = Integer.valueOf(splitReservation[2]);
temp.time = splitReservation[3];
list.addArrayItem(i, temp);
i++;
}
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
ReservationList.sortArray(list); // this is a static method, so treat it like one

Related

Searching an array for the number of occurrences that a string appears

In my java class, we are using junit test to test our methods. This section introduced using an interface.
this specific method I am having problems on is supposed to search an array at each index, looking for a matching string as the input.
In the junit test I have
void test()
{
MyClassList labTest = new MyClassList("CIS 120", "Fall", "Professor Awesome");
MyStudent george = new MyStudent("George","Lucas", "555-555-5555","george.lucas#starwars.com");
MyStudent gene = new MyStudent("Gene", "Roddenberry","666-666-6666", "gene.roddenberry#startrek.com");
MyStudent jordan = new MyStudent("Jordan" ,"Robberts", "755-555-5555", "jordan.robberts#wheeloftime.com");
labTest.insert(george);
labTest.insert(gene);
labTest.insert(jordan);
System.out.println(labTest.toString());
System.out.println(labTest.contains(george));
System.out.println(labTest.search("George"));
This is the code U have for the method search:
Note
protected MyStudent [] log;
protected int lastIndex = -1;
are global variables
package Lab2;
import java.util.Arrays;
import java.util.Scanner;
import Lab2.ClassListInterFace;
public class MyClassList implements ClassListInterFace {
protected String course;
protected String semester;
protected String teacherLastName;
protected MyStudent[] log;
protected int lastIndex = -1;
public MyClassList(String currCourse, String currSemester, String lastName, int maxSize) {
log = new MyStudent[maxSize];
this.course = currCourse;
this.semester = currSemester;
this.teacherLastName = lastName;
}
public MyClassList( String currCourse, String currSemester, String lastName)
{
log = new MyStudent[100];
this.course = currCourse;
this.semester = currSemester;
this.teacherLastName = lastName;
}
public void insert(MyStudent element) {
lastIndex++;
log[lastIndex] = element;
}
public boolean isFull() {
if (lastIndex == (log.length - 1))
return true;
else
return false;
}
public int size() {
return (lastIndex + 1);
}
public void clear()
{
for (int i = 0; i <= lastIndex; i++)
log[i] = null;
lastIndex = -1;
}
public String getName() {
return teacherLastName;
}
public boolean contains(MyStudent element) {
boolean found = false;
for( int location = 0;location <= lastIndex; location++)
{
if (element.equals(log[location])) // if they match
found = true;
}
return found;
}
public String toString()
{
String message = "Course " + course + "\n Semester " + semester + "\n Proffessor " + teacherLastName + "\n";
for (int i = 0; i <= lastIndex; i++) {
message += log[i].toString();
}
return message;
}
public int search(String x)
{
int answer = 0;
for(int i = 0; i < log.length; i++)
{
if(x.equalsIgnoreCase(log[i]))
answer++;
}
return answer;
}
I got this based off some code that the teacher gave us for reference, and I tweaked it a little.
This looks like something that can be done much more elegantly with a for loop. In my experience, using a more concise control structure designed for things like this can lead to far fewer chances of errors. While I'm not sure what exact issue you are looking for help with, I do notice that if you do find a match, you skip the next element without checking to see if it is also a match.
int location = 0;
while (location <= lastIndex)
{
if (x.equalsIgnoreCase(log[location]))
{ // if they match
answer ++;
location ++; //<-- Here's where you increment twice upon finding a match!
}
location++; //To fix with the smallest number of changes, just put this in an else clause
}
This entire block can be reduced to approximately half the lines and half the variables by changing it up to be a for loop. See below:
for(int i = 0; i < log.length; i++) {
if(x.equalsIgnoreCase(log[i].firstName))
answer++;
}
This is much easier to read, and far less prone to errors. Trying to keep track of an excessive number of variables or dividing out common operations (such as incrementing where you are) is just asking for issues. This four-liner is functionally equivalent to your above code block (aside from the fact it doesn't skip the following entry when it finds a match), yet has far fewer opportunities for a programmer to make a mistake. Always, when you can get away with it, use the control flow structure designed for the task.

Displaying the names and times of the first and second winners of a marathon

Locked for 9084 days. There are disputes about this question’s content being resolved at this time. It is not currently accepting new answers or interactions.
I would like your help here guys
/**
* In this assignment I am supposed to display the names and times of the first and second winners (2 best times) of a marathon
* But I am struggling with the second one
*/
public class MitAssignment3Chapter7 {
public static void main(String args[]){
String runners[] = {"Gene","Elvis","Presley","Felicity","Welcome"};
int[] timeInMinutes = {40,50,76,56,62};
int index = 0;
int a = 0;
int first = timeInMinutes[1];
for (a = 0 ; a < timeInMinutes.length; a++){
if ( first > timeInMinutes[a]){
index = a;
first = timeInMinutes[index];
}
// if (first < timeInMinutes[a] && timeInMinutes[a]) Trying to do the second here
}
System.out.println("The winner of the marathon is: "+runners[index]+" with "+timeInMinutes[index]+" minutes");
}
}
Locked for 9084 days. There are disputes about this answer’s content being resolved at this time. It is not currently accepting new interactions.
using other collections would be easy.. but you can do it with simple arrays also.. not only second one, you can find all ranks of runners by sorting arrays.. check this code..
public static void main(String args[]) {
String runners[] = { "Gene", "Elvis", "Presley", "Felicity", "Welcome" };
int[] timeInMinutes = { 40, 50, 76, 56, 62 };
int a = 0;
int tempTime = 0;
String tempRunner = "";
for (int i = 0; i < timeInMinutes.length; i++) {
for (int j = i + 1; j < timeInMinutes.length; j++) {
if (timeInMinutes[i] > timeInMinutes[j]) {
tempTime = timeInMinutes[i];
timeInMinutes[i] = timeInMinutes[j];
timeInMinutes[j] = tempTime;
tempRunner = runners[i];
runners[i] = runners[j];
runners[j] = tempRunner;
}
}
}
for (int index = 0; index < runners.length; index++)
System.out.println("Rank " + (index+1) + ": " + runners[index] + " with " + timeInMinutes[index] + " minutes");
}
You can find the winner first, after you had found out winner, take winner out of your time array and find the fastest people in your current array, it will be the second player.
You can create a new class to hold result time and the name. Implement compareTo method for this class. Populate new List with all the results and sort the one. Now it's possible to get any Nth result(time and name).
static class Result implements Comparable<Result> {
private final int time;
private final String name;
Result(int time, String name) {
this.time = time;
this.name = name;
}
int getTime() { return time; }
String getName() { return name; }
#Override
public int compareTo(Result o) {
return Integer.compare(time, o.time);
}
}
public static void main(String args[]){
String runners[] = {"Gene","Elvis","Presley","Felicity","Welcome"};
int[] timeInMinutes = {40,50,76,56,62};
List<Result> results = new ArrayList<>(runners.length);
for (int i = 0; i < runners.length; i++) {
results.add(new Result(timeInMinutes[i], runners[i]));
}
Collections.sort(results);
Result second = results.get(1);
System.out.println("Second winner: " + second.getName() + "; Time: " + second.getTime());
}

Java objects and 2D arrays

I am working on my A-Level computing project, and I have a 2D array, with in the x direction name, password, state (just a variable). I want to sort the 2D array using a bubble sort so that I can implement a binary search on the data. Here is the code I have come up with:
public String[][] sort(String[][] details, int len){
boolean flag = false;
String[] temp = new String[3];
int z=0;
do{
flag = false;
for (int i = 0; i < len; i++){
if(details[0][i].charAt(0) > details[0][i + 1].charAt(0)){
flag = true;
temp[0] = details[0][i];
temp[1] = details[1][i];
temp[2] = details[2][i];
details[0][i] = details[0][i + 1];
details[1][i] = details[1][i + 1];
details[2][i] = details[2][i + 1];
details[0][i + 1] = temp[0];
details[1][i + 1] = temp[1];
details[2][i + 1] = temp[2];
}
}
len--;
} while (flag);
return details;
}
However it has sort of come to my attention I could do this much easier using object orientation which is something I would love to try and have a go at. Does anyone know where I could start learning about object orientation in this sort of context, the guides I have searched for online, just talk about shapes etc... and I am really not sure how to implement those guides into this situation.
From my understanding, what I could do is set up an object with three variables, name, password and state; and when I called upon a name, I could also get the details for the password and state. Am I along the right lines here? and if so can anyone show me how I can do this please.
Thanks a lot.
Sam
edit -
Thanks for all the help guys, thanks to this, I have worked out how to implement this in my project, and it is amazing how much easier it makes the code! Thanks a lot!
For anyone else struggling with this problem, this is my final code:
public class loginDetailsOO {
public static void main (String[] args){
loginDetailsOO object = new loginDetailsOO();
object.run();
}
public void run(){
String password = encrypt("password");
String location = "textFiles\\PasswordScreen.txt";
int lines = numberOfLines(location);
User[] user = fileToArray(location, lines);
int index = searchForUsername(user, lines / 4, "VELINGUARD");
if (password.equals(user[index].getPassword())){
System.out.println("entrance is granted");
}
User u = new User("ball", "pass", 0);
addToFile(u, "VELINGUARD");
}
public void addToFile(User newUser, String currentUsername){
String location = "textFiles\\PasswordScreen.txt";
newUser.setUsername(newUser.getUsername().toUpperCase());
int lines = numberOfLines(location);
User[] user = fileToArray(location, lines);
int line = lines / 4;
int index = searchForUsername(user, line, currentUsername);
if (user[index].getState() == 1){
if (searchForUsername(user,line, newUser.getUsername()) == -1) {
newUser.setPassword(encrypt(newUser.getPassword()));
user[line] = newUser;
user = sort(user, line);
writeToFile(location, user, line);
} else {
System.out.println("User already exists");
}
} else {
System.out.println("Permission not granted");
}
}
public User[] sort(User[] user, int len){
boolean flag = false;
User temp;
int z=0;
do{
flag = false;
for (int i = 0; i < len; i++){
if(user[i].getUsername().compareTo(user[i + 1].getUsername()) > 0){
flag = true;
temp = user[i];
user[i] = user[i + 1];
user[i + 1] = temp;
}
}
len--;
} while (flag);
return user;
}
public String encrypt (String password){
String encrypted = "";
char temp;
int ASCII;
for (int i = 0; i < password.length(); i++){
temp = password.charAt(i);
ASCII = (int) temp;
if (ASCII >= 32 && ASCII <= 127)
{
int x = ASCII - 32;
x = (x + 6) % 96;
if (x < 0)
x += 96; //java modulo can lead to negative values!
encrypted += (char) (x + 32);
}
}
return encrypted;
}
public String decrypt (String password){
String decrypted = "";
char temp;
int ASCII;
for (int i = 0; i < password.length(); i++){
temp = password.charAt(i);
ASCII =(int) temp;
if (ASCII >= 32 && ASCII <= 127)
{
int x = ASCII - 32;
x = (x - 6) % 96;
if (x < 0)
x += 96;
decrypted += (char) (x + 32);
}
}
return decrypted;
}
public User[] fileToArray(String file, int lines) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(file)));
int line = lines / 4;
String temp[] = new String[3];
User[] user = new User[line];
for (int i = 0; i < line; i++){
temp[0] = reader.readLine();
temp[1] = reader.readLine();
temp[2] = reader.readLine();
reader.readLine();
user[i] = new User(temp[0], temp[1], Integer.parseInt(temp[2]));
}
return user;
} catch(Exception e){
System.out.println("File not found");
return null;
}
}
public void writeToFile(String location, User[] user, int length){
try {
File f = new File(getClass().getResource(location).toURI());
f.setWritable(true);
FileWriter w = new FileWriter(f);
BufferedWriter writer = new BufferedWriter(w);
wipeFile(f);
for (int i = 0; i <= length; i++){
writer.write(user[i].getUsername());
writer.newLine();
writer.write(user[i].getPassword());
writer.newLine();
writer.write(user[i].getState());
writer.newLine();
writer.write("-");
writer.newLine();
}
writer.close();
f.setReadOnly();
} catch(Exception e){System.out.println("error writing to file");}
}
public void wipeFile(File f) {
try {
PrintWriter wiper = new PrintWriter(f);
wiper.println("");
} catch (Exception ex) {
System.out.println("error wiping file");
}
}
public int searchForUsername(User[] user, int lines, String name){ //implements binary search
int low = 0;
int high = lines - 1;
int mid;
while (low <= high){ //by using a while loop it means if it is an empty file than there will be no issue
mid = low + high;
mid = mid / 2;
if ((int) name.charAt(0) > (int) user[mid].getUsername().charAt(0)){
low = mid + 1;
} else if ((int) name.charAt(0) < (int) user[mid].getUsername().charAt(0)) {
high = mid - 1;
} else {
if (user[mid].getUsername().equals(name)){
return mid;
}
else {
int pass = 0;
do{
if (user[mid - pass].getUsername().equals(name)){
return mid - pass;
} else if (user[mid + pass].getUsername().equals(name)) {
return mid + pass;
}
} while (true);
}
}
}
System.out.println("Name not found");
return -1;
}
public int numberOfLines(String file) {
try{
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(getClass().getResourceAsStream(file)));
lnr.skip(Long.MAX_VALUE);
int length = (lnr.getLineNumber() + 1); //Add 1 because line index starts at 0
lnr.close();
return length;
}catch(Exception e){
System.out.println("File not Found");
return 0;
}
}
and:
public class User{
private String username;
private String password;
private int state;
public User(){
username = "";
password = "";
state = 0;
}
public User(String user, String pass, int st){
username = user;
password = pass;
state = st;
}
public void setUsername(String name){
username = name;
}
public void setPassword(String pass){
password = pass;
}
public void setState(int st){
state = st;
}
public String getUsername(){
return username;
}
public String getPassword(){
return password;
}
public int getState(){
return state;
}
Bubble sort is meant to be used in only one context in Computer Science, as an example of how simple approaches can sometimes be the worst approach. If you don't remember anything else about sorting, remember that you should never use bubble sort (quicksort is almost always a safer bet).
In order to do this with object orientation, you need objects. These are the code equivalent of which "nouns" are going to be describing the problem. This might mean you would need (minimally) a:
List
Entry
Comparison (Thing)
The problem is that the ordering of something is an action (a verb) and not typically a noun. However, we can make it a noun (thank you English for having "gerunds"). This adds:
Sorter (an interface)
BubbleSorter (ick, yuck, boo!)
QuickSorter
HeapSorter
The main problems come into play when one realizes that without information hiding you don't have much in the way of Object-Orientation. To do this many of the items would require their data being private, and it is something of a try a few times to find the right balance between the "data structure" approach of all exposed data and the OO approach of all private data.
A very pure OO-approach might look like:
class Book extends Entry {
public String getTitle() {
...
}
}
List<Book> books = new List<Book>();
books.add(new Book(...));
books.add(new Book(...));
books.add(new Book(...));
Sorter sorter = new QuickSorter();
Comparison<Book> byTitle = new Comparison<Book>() {
public int compare(Book one, Book two) {
return String.compare(one.getTitle(), two.getTitle());
}
}
sorter.sort(books, byTitle);
Of course, there are different things that people value, and so they might come up with valid, but entirely different OO structures.
Finally, there is already a very good OO-ish set of data structure in java.util, and while it may be fun to create a new one, one should use the java.util.List and friends because they already implement the fastest sorting algorithms (in Collections.sort) and most other libraries expect a java.util.List and not a my.custom.List.
Have fun, and happy hacking!
Make a Detail class that stores the details you are currently storing in an array. Something like:
public class Detail {
public String name;
public String password;
public String state;
}
Then modify your existing code to work with Detail objects instead of arrays of arrays.
public Detail[] sort(Detail[] details){
boolean flag = false;
do{
flag = false;
for (int i = 0; i < details.length; i++){
if(details[i].name.compareTo(details[i + 1].name) > 0){
flag = true;
Detail temp = details[i];
details[i] = details[i + 1];
details[i + 1] = temp;
}
}
len--;
} while (flag);
return details;
}
Note that it would be even better to just use a library function to sort the array, but if you want to do it this way to learn about bubble sort, that's fine.
You will probably need to modify the other parts of your code to use Detail objects as well.

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

Java finding place in an array?

So I have to find the minimum in an array in Java, but with that I have to print out the corresponding names that go with the minimum in another parallel array. Inside my for loop where I find the minimum, I have a variable place that I set equal to my counter variable from the for loop when the minimum is changed. But every time I print out the name, it prints out the first name in the array instead of the name in the place holder.
public double getMinimum(double[] money)
{
double lowest = money[0];
for (int p = 0; p < money.length; p++)
{
if (money[p] < lowest)
{
lowest = money[p];
place = p;
}
}
return lowest;
}
Theres the for loop within my programmer-defined class that finds the minimum.
public String getFirstNameMin(String[] firstName)
{
String minFirstName;
minFirstName = firstName[place];
return minFirstName;
}
This is the code I'm using to figure out the first name from the first names array at that place. What am I doing wrong? I'm kinda new to Java, but I did all this array stuff in C++ before, so idk if I am missing something very simple, or its different in Java.
I would say try making a separate class for this that contains the user and the money:
public class User {
private double money;
private String fname;
private String lname;
//getters/setters/constructors
}
Then from there you can simply compare the accounts:
public User getMinimum(User[] users) {
if (users.length <= 0) {
return null;
}
User lowest = users[0];
for (int i = 1; i < users.length; i++) {
if (users[i].getMoney() < lowest.getMoney()) {
lowest = users[i];
}
}
return lowest;
}
Try this:
public int getMinIndex(double[] money)
{
double min = money[0];
int minIndex = 0;
for (int p = 0; p < money.length; p++)
{
if (money[p] < min)
{
min = money[p];
minIndex = p;
}
}
return minIndex;
}
public static void main(String[] args)
{
double[] money;
String[] name;
//... init your arrays here!
int index = getMinIndex(money);
System.out.println("Min money = " + money[index] + "; name = " + name[index]);
}
However, following an object oriented approach rogues solution is much nicer!!!

Categories

Resources