Accessing array of objects from another class - java

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

Related

Implementation of Radix sort in Java using Nodes instead of integers

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[].

Iterate through ArrayList

I'm currently trying to iterate through an ArrayList and see if it contains the following numbers I input into the winners array. However, the ticket object won't allow me to utilize the .contains() method which is where I'm getting the error. Any idea on how to work around this?
int[] winners = new int[6];
for(int i = 0; i < winners.length; i++)
{
winners[i] = in.nextInt();
}
in.close();
Scanner scan = new Scanner(file);
ArrayList<Ticket> info = new ArrayList<Ticket>();
for(int i = 0; i < lim; i++)
{
String name = scan.nextLine();
String num = scan.nextLine();
String[] t = num.split(" ");
int[] tichold = new int[t.length];
for(int j = 0; j < t.length; j++)
{
tichold[j] = Integer.parseInt(t[j]);
}
Ticket ticket = new Ticket(name, tichold);
info.add(ticket);
}
**for(Ticket t : info)
{
if(t.contains(winners))
{
System.out.println("Yes");
}
}**
scan.close();
}
**public static class Ticket
{
public String name;
public int[] tarray;
public Ticket(String name, int[] tarray)
{
this.name = name;
this.tarray = tarray;
}**
You can't use a method that doesn't exist for that class. Since you don't have contains defined for Ticket, I'm not surprised that it isn't working.
From inference, winners is an int[]. In that case, you'd define a new method contains inside of Ticket.
public boolean contains(int[] winningNumbers) {
// logic here
}
Depending on how the winning numbers for a given ticket are stored, and given how you define different conditions of winning, you'd handle your logic here.
If they're stored as an array and you want an exact match, then you can use Arrays.equals for that.
public boolean contains(int[] winningNumbers) {
return Arrays.equals(numbers, winningNumbers);
}
Try this Ticket class with and added contains method:
public class Ticket {
public String name;
public int[] tarray;
public Ticket(String name, int[] tarray)
{
this.name = name;
this.tarray = tarray;
}
public boolean contains(int[] winners) {
for (int i = 0; i < winners.length; i++) {
for (int j = 0; j < tarray.length; j++) {
if (winners[i] == tarray[j])
return true;
}
}
return false;
}
}

How to find index of STRING array in Java from a given value?

I wanted to know if there's a native method in array for Java to get the index of the table for a given value ?
Let's say my table contains these strings :
public static final String[] TYPES = {
"Sedan",
"Compact",
"Roadster",
"Minivan",
"SUV",
"Convertible",
"Cargo",
"Others"
};
Let's say the user has to enter the type of car and that then in the background the program takes that string and get's it's position in the array.
So if the person enters : Sedan
It should take the position 0 and store's it in the object of Cars created by my program ...
Type in:
Arrays.asList(TYPES).indexOf("Sedan");
String carName = // insert code here
int index = -1;
for (int i=0;i<TYPES.length;i++) {
if (TYPES[i].equals(carName)) {
index = i;
break;
}
}
After this index is the array index of your car, or -1 if it doesn't exist.
for (int i = 0; i < Types.length; i++) {
if(TYPES[i].equals(userString)){
return i;
}
}
return -1;//not found
You can do this too:
return Arrays.asList(Types).indexOf(userSTring);
I had an array of all English words. My array has unique items. But using…
Arrays.asList(TYPES).indexOf(myString);
…always gave me indexOutOfBoundException.
So, I tried:
Arrays.asList(TYPES).lastIndexOf(myString);
And, it worked. If your arrays don't have same item twice, you can use:
Arrays.asList(TYPES).lastIndexOf(myString);
try this instead
org.apache.commons.lang.ArrayUtils.indexOf(array, value);
Use Arrays class to do this
Arrays.sort(TYPES);
int index = Arrays.binarySearch(TYPES, "Sedan");
No built-in method. But you can implement one easily:
public static int getIndexOf(String[] strings, String item) {
for (int i = 0; i < strings.length; i++) {
if (item.equals(strings[i])) return i;
}
return -1;
}
There is no native indexof method in java arrays.You will need to write your own method for this.
An easy way would be to iterate over the items in the array in a loop.
for (var i = 0; i < arrayLength; i++) {
// (string) Compare the given string with myArray[i]
// if it matches store/save i and exit the loop.
}
There would definitely be better ways but for small number of items this should be blazing fast. Btw this is javascript but same method should work in almost every programming language.
Try this Function :
public int indexOfArray(String input){
for(int i=0;i<TYPES,length();i++)
{
if(TYPES[i].equals(input))
{
return i ;
}
}
return -1 // if the text not found the function return -1
}
Testable mockable interafce
public interface IArrayUtility<T> {
int find(T[] list, T item);
}
implementation
public class ArrayUtility<T> implements IArrayUtility<T> {
#Override
public int find(T[] array, T search) {
if(array == null || array.length == 0 || search == null) {
return -1;
}
int position = 0;
for(T item : array) {
if(item.equals(search)) {
return position;
} else {
++position;
}
}
return -1;
}
}
Test
#Test
public void testArrayUtilityFindForExistentItemReturnsPosition() {
// Arrange
String search = "bus";
String[] array = {"car", search, "motorbike"};
// Act
int position = arrayUtility.find(array, search);
// Assert
Assert.assertEquals(position, 1);
}
Use this as a method with x being any number initially.
The string y being passed in by console and v is the array to search!
public static int getIndex(int x, String y, String[]v){
for(int m = 0; m < v.length; m++){
if (v[m].equalsIgnoreCase(y)){
x = m;
}
}
return x;
}
Refactoring the above methods and showing with the use:
private String[] languages = {"pt", "en", "es"};
private Integer indexOf(String[] arr, String str){
for (int i = 0; i < arr.length; i++)
if(arr[i].equals(str)) return i;
return -1;
}
indexOf(languages, "en")

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!!!

Identify an item from array?

I have 3 arrays, working parallel. I need to give the user the ability to identify an item from the array, and remove it and its information, and or edit its information.
This is what I have so far:
private static int identifyComputer(String[] computerBrand, double[] computerSpeed, double[] computerPrice) {
Scanner keyboard = new Scanner(System.in);
int counter = computerBrand.length;
System.out.println("Computer brand?");
String cb = keyboard.nextLine();
int i = 0;
boolean notFound = true;
for (i = 0; i < counter && notFound; i++)
{
if (cb.equals(computerBrand[i]))
{
System.out.println(computerBrand[i]);
System.out.println(computerSpeed[i]);
System.out.println(computerPrice[i]);
notFound = false;
}
if (notFound) {
return -1;
}
else
{
System.out.println("Computer Speed?");
String cs = keyboard.nextLine();
boolean notFound2 = true;
for (i = 0; i < counter && notFound2; i++)
{
if (cs.equals(computerSpeed[i]))
{
System.out.println(computerBrand[i]);
System.out.println(computerSpeed[i]);
System.out.println(computerPrice[i]);
notFound2 = false;
}
}
if (notFound) {
return -1;
} else {
System.out.println("Computer Price?");
String cp = keyboard.nextLine();
boolean notFound3 = true;
for (i = 0; i < counter && notFound3; i++)
{
if (cp.equals(computerPrice[i]))
{
System.out.println(computerBrand[i]);
System.out.println(computerSpeed[i]);
System.out.println(computerPrice[i]);
notFound3 = false;
}
}
if (notFound) {
return -1;
}
}
}
}
return i;
}
But I know that isnt how you do it 100%. It has some errors on the for loops and it doesnt work correctly. I was trying to get the user to be able to indentify the computer and return the index of that computer. But I am also unsure of that too.
(I CANNOT USE ARRAYLISTS)
It's confusing to store the information in three arrays in parallel. I strongly recommend you create a new type of object with all the information, and create a single array of that object:
class Computer {
String brand;
int speed;
double price;
}
Next, create an array of Computer objects and manipulate the variables in class Computer through that array. Your code will be much easier to write.

Categories

Resources