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!!!
Related
i'm stuck on this code. I'm trying to access an array of objects from another class and compare it in my method.
public static double averageUserscore(GameScore[] scores, int numScores, String name) {
double sum;
int playerScores = 0;
for(int i = 0; i < numScores;) {
if(???? == name) {
sum = sum + scores[i];
playerScores++;
}
}
}
I want to compare [i]th GameScore userName which is in another class to name.
This code should work. To compare Strings in java do not use ==
for(int i = 0; i < numScores;) {
if(scoares[i].getUserName().equals(name)) {
sum = sum + scores[i].getUserScore();
playerScores++;
// maybe break; if only one that should match
}
}
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.
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
I have a final project for my Data Structures class that I can't figure out how to do. I need to implement Radix sort and I understand the concept for the most part. But all the implementations I found online so far are using it strictly with integers and I need to use it with the other Type that I have created called Note which is a string with ID parameter.
Here is what I have so far but unfortunately it does not pass any JUnit test.
package edu.drew.note;
public class RadixSort implements SortInterface {
public static void Radix(Note[] note){
// Largest place for a 32-bit int is the 1 billion's place
for(int place=1; place <= 1000000000; place *= 10){
// Use counting sort at each digit's place
note = countingSort(note, place);
}
//return note;
}
private static Note[] countingSort(Note[] note, long place){ //Where the sorting actually happens
Note[] output = new Note[note.length]; //Creating a new note that would be our output.
int[] count = new int[10]; //Creating a counter
for(int i=0; i < note.length; i++){ //For loop that calculates
int digit = getDigit(note[i].getID(), place);
count[digit] += 1;
}
for(int i=1; i < count.length; i++){
count[i] += count[i-1];
}
for(int i = note.length-1; i >= 0; i--){
int digit = getDigit((note[i].getID()), place);
output[count[digit]-1] = note[i];
count[digit]--;
}
return output;
}
private static int getDigit(long value, long digitPlace){ //Takes value of Note[i] and i. Returns digit.
return (int) ((value/digitPlace ) % 10);
}
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
//Main Method
public static void main(String[] args) {
// make an array of notes
Note q = new Note(" ", " ");
Note n = new Note("CSCI 230 Project Plan",
"Each person will number their top 5 choices.\n" +
"By next week, Dr. Hill will assign which piece\n" +
"everyone will work on.\n");
n.tag("CSCI 230");
n.tag("final project");
Note[] Note = {q,n};
//print out not id's
System.out.println(Note + " Worked");
//call radix
Radix(Note);
System.out.println(Note);
//print out note_id's
}
}
Instead of
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
I should have used
public Note[] sort(Note[] s) { //
s = Radix(s);
return s;
}
and change the variable type of Radix from void to Note[].
I am trying to go through a list of names with amounts.
One array has the name of the person , the other has the amount the person gave i.e. john, 55 sally 40 john 33 sarah 55.
My objective is to total the like names and print out the name of the person and the total amount that was given.
John gave twice so he should total 88. But I am getting the total right but my program is printing the name twice. So john 88 is printing twice... I know its likely because I put it in the first for loop its iterating the entire length of the array.
But I am unsure how to solve this?
import java.util.*;
public class chapterfive {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
String[]names = new String[4];
int[] scores = new int[4];
for (int i = 0; i<names.length; i++) {
names[i] = in.next();
scores[i] = in.nextInt();
}
int amount = 0;
String firstname = "";
for (int i = 0; i < names.length; i++) {
for (int j=0; j < names.length; j++) {
if (names[j].equals(names[i]))
amount += scores[j];
}
System.out.println(names[i] + " " + amount);
amount = 0;
}
}
}
You can see that they have a relationship like Name -> Score , so if you think more abstract this is a dictionary with Key (Name) and Value (Score) , so you can use another data-structure like a Map or you can use an array and make a class Person , have the arrayOrderer and when you add a new person check if that person exist in the array..
Example :
Map <String , Integer> people = new HashMap<>();
for (int i=0; i<lengthYouWant; i++)
{
String name=in.next();
int score=in.nextInt();
if(people.contains(name)){
score= people.get(name)+score;
}
people.put(name,score);
}
Should be using a Map to simplify things, rather than keeping track of two arrays. But heres a fix that may work (haven't tested it)
String firstname = "";
for (int i = 0; i < names.length; i++) {
int amount = 0;
boolean skip = false;
for (int j=0; j < names.length; j++) {
//need to skip because we have already processed it
if(names[j].equals(names[i]) && i > j) {
skip = true;
break;
}
else if (names[j].equals(names[i])) {
amount += scores[j];
}
}
if(!skip) {
System.out.println(names[i] + " " + amount);
}
}
If you make an array or list of the Person class you can implement Comparable and add a method to help in sorting.
Java is an object-oriented language, which means, among other things, that you can make your own data structures. Using parallel arrays is error prone, and it separates data you want to keep together. So, what do you need to organize this?
First is a way of storing a name and an amount. Call it Donation.
class Donation {
private final String name;
private final int amount;
public Donation(String name, String amount) {
this.name = name;
this.amount = amount;
// EXERCISE: Add error checking.
}
public String getName() { return name; }
public int getAmount() { return amount; }
public String toString() {
return "Name: " + name +", amount: " + amount;
}
}
Notice that this class's variables are final; they can't be changed once set. They are set in the constructor, and there are get methods and a toString method that replaces what you have in your System.out.println statement.
Next, you need a way of storing the data. Don't use arrays. Lists are more flexible.
private static List<Donation> donations = new ArrayList<Donation>();
// and in main:
while (true) {
String name = null;
int amount = 0;
if (in.hasNext()) {
name = in.next();
} else {
break;
}
if (in.hasNextInt()) {
amount = in.nextInt();
} else {
break;
}
donations.add(new Donation(name, amount));
} See -- no 4s.
Next, you need to consolidate the repeated donations. I mean, some people give to their church every Sunday. We'll use the appropriate structure, a Map.
// Also in main:
Map<String, Integer> totals = new HashMap<>();
for(Donation d: donations) {
String name = d.getName();
int amount = d.getAmount();
if (!totals.containsKey(name)) {
totals.put(name, 0);
}
int currentDonation = totals.get(name);
totals.put(name, currentDonation + amount);
}
And then finally, you iterate through the map and print each entry.
for ( Map.Entry<String, Integer> entry: totals.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
And now, another exercise and strategy: stop doing everything in main. Give your ChapterFive class instance variables and methods. Then, write tests for these. Try to find improvements to what I suggested. Then, see if there are libraries that can help you.