returning arrays in java? - java

In my program I am trying to return the prevScore[i] and the prevScoreName[i]. However, both return statements have errors stating that they're incompatible types (required int[], found int). I feel like it may be how I defined them in the main project (first 2 lines below). Any help would be appreciated.
prevScore = scoreChange (prevScore, score);
prevScoreName = nameChange (prevScoreName, newName);
public static int[] scoreChange (int prevScore[], int score)
{
for (i=1; i<prevScore.length;i++){
prevScore[i] = score;
}
return prevScore[i];
}
public static String[] nameChange (String prevScoreName[], String newName)
{
for (i=1; i<prevScoreName.length;i++){
prevScoreName[i] = newName;
}
return prevScoreName[i];
}

If you want to return just one item from each function, change the return types to int and String (not int[] and String[]). If you want to return whole arrays, then change the return statements to return prevScore; and return prevScoreName; (without the [i]).
Note that there's no need to return the whole array - the caller already has a reference to it. Just change the return types to void, delete the return statements, and get rid of the assignments in front of your calls.

You are not returning the arrays:
return prevScoreName[i]; // Returns the String at index 'i'
return prevScore[i]; // Returns the integer at index 'i'
If you want to return actual arrays, you need to lose the [i]:
return prevScoreName; // Returns the array
return prevScore; // Returns the array
Additionally, there is no need to even return anything:
prevScore = scoreChange (prevScore, score);
prevScoreName = nameChange (prevScoreName, newName);
You are modifying the contents of these arrays with the function calls.

It seems like you maybe don't understand arrays.
When you say
public static int[] you are making reference to an entire array. (not all of its contents, but rather you are pointing to the space in memory where the array lives.)
When you say
public static int you are referring to just one integer.
In your method, you declared your return type as int[], which meant you were returning an entire array of integers. But your return statement was trying to return prevScore[i], which is a single integer, that just happens to be contained in the array. It would have been the same if you had wrote:
int var = prevScore[i];
return var;
Its easier to see that you are returning an integer in this example.
An array of integers is not the same as an integer, so your compiler didn't know what to do when you tried to send back a single integer when it was expecting to see an array of integers.

Related

Accessing an array java

for(int i=0;i<dictionary.words.length;i++){
if(dictionary.words[i].length() <=maxWordlength){
count++;
smallWordDictionary[i]=dictionary.words[i];
}
}
I used this code to store the strings from a dictionary array into an array containing strings with a shorter word length. I now want to pass this array alongside a random number to the following method(to create a randomly generated word):
randomWord(smallWordDictionary, outcome);
When I use the following method:
static void randomWord(String [] array, int number){
System.out.println(array[number]);
}
The console prints out null and I'm not sure why. How can I get the console to print out a string that corresponds to its element within the smallWordDictionary array?
You're not storing anything in smallWordDictionary[i] when the length is more than maxWordlength.
The default value for your array members is null, not empty string. (The default value for any array members of reference type is null.)
Consequently, some of your random indices will point to an array member that is still null.
Solutions include:
Build a smaller array, that includes only the words that passed. No nulls will be present.
Place empty string in each member that does not pass.
Check for null when printing.
Build a smaller array
The easiest way to do this is with a List.
List<String> smallWordList = new ArrayList<>;
for(int i=0;i<dictionary.words.length;i++){
if(dictionary.words[i].length() <=maxWordlength){
count++;
smallWordList.add( dictionary.words[i] );
}
}
smallWordDictionary = smallWordList.toArray( new String[] );
Note that count is the sames as smallerWords.size() or smallerWordDictionary.length.
Place empty string in each member that does not pass
for(int i=0;i<dictionary.words.length;i++){
if(dictionary.words[i].length() <=maxWordlength){
count++;
smallWordDictionary[i]=dictionary.words[i];
}
else {
smallWordDictionary[i]="";
}
}
Check for null when printing
static void randomWord(String [] array, int number){
String member = array[number];
System.out.println( (null == member) ? "" : member);
}

Java : Array items null and int values

I have an array with type Object. Then I assign it's values to null. But later I want to assign int values on null cells. Is that possible?
In these lines:
Queue[y]=new Int;
Queue[y]=num;
I am trying create an object Int type, in the null cell. But I get this error:
error: '(' or '[' expected
Queue[y]=new Int;
private Object Queue[];
public PriorityQueue(int capacity){
this.capacity=capacity;
Queue= new Object [capacity];
for(int i=0;i<=Queue.length;i++) {
Queue[i]=null;
}
}
public boolean insert(int num){
if (y<capacity){
Queue[y]=new Int;
Queue[y]=num;
y++;
return true;
}
else{
y++;
return false;
}
}
(I don't know what class you mean by Int - perhaps you mean java.lang.Integer, but perhaps you mean some custom class. It's not totally relevant to the answer, however)
You always need a parameter list when you invoke a constructor, even if it is empty:
new Int()
Or, if you mean to create an array, you need to specify the number of elements:
new Int[10]
However, you don't need the first assignment:
Queue[y]=new Int();
Queue[y]=num;
The second line overwrites the value in the first line, so it's actually just creating an object and then immediately discarding it.
You could simply write:
Queue[y]=num;
Note that this isn't actually assigning an int to an Object array element: due to autoboxing, the compiler automatically converts this to:
Queue[y]=Integer.valueOf(num);
so an instance of Integer is being added to the array. However, this conversion isn't something that you need to do yourself.

Having trouble with chaining method calls in Java

I am working on an assignment that requires me to call a findInventoryItem method to search for an item by part number, and then use the getQuantity method in another class to find the quantity of said item. I am having trouble putting this concept of chaining together. Since the findInventoryItem method's data type is an object, how do I get the quantity of the object to be returned as an integer?
This is what I have so far, intending on adding a check for a non zero quantity in an if loop.
public int numberInInventory(int partNumber)
{
findInventoryItem(partNumber).getQuantity();
}
Here is the getQuantity in the other class.
public int getQuantity()
{
return quantity;
}
Here is the findInventoryItem method.
public InventoryItem findInventoryItem(int searchPartNumber)
{
int index = 0;
while (index < items.size()){
InventoryItem inventoryItem = items.get(index);
int fetchedPartNumber = inventoryItem.getPartNumber();
if(fetchedPartNumber == searchPartNumber){
return inventoryItem;
}
else{
index++;
}
}
return null;
}
You seem to have just not understood how expressions work.
Since the findInventoryItem method's data type is an object, how do I get the quantity of the object to be returned as an integer?
findInventoryItem does return an object, but we then call getQuantity() on that object, which (presumably) returns an integer. As a result, the expression you have evaluates to an int.
The code you have at the moment is really just a shorthand for:
WhateverThatObjectClassIs item = findInventoryItem(partNumber);
item.getQuantity();
Now (hopefully) you can see that all you need to do is assign the result of your expression to a variable:
int quantity = findInventoryItem(partNumber).getQuantity();
And you're done.

What type to return?

Consider a method which produces different types of results. In my case it's either an ArrayList or an Integer (pseudo code):
int a = ... // value for a comes from another function
public ArrayList compute(){ // return either ArrayList or Integer
if(a==1){
ArrayList result = new Arraylist()
for(int i=0; i<=something; i++){
arr.add(...);
}
}
if(a==2){
int result;
result = somethingElse;
}
return result;
}
Depending on the result of a, the result of result comes either from a loop and loads the results into an ArrayList, or in the second case it will just be a single number.
What type should the method return?
Return a List<Integer>. For a single integer simply return a list with a single element.
An alternative to returning a List (but "functionally" the same),
public void compute(List<Integer> result){
// add/remove/set the given list,
}
And although this looks like a bad design in general, you may in this case actually return a value that indicates if a "list" or a single value (a list with one element) is returned.
public boolean compute(List<Integer> result){ ...
Or, better, the length of the list (depends on what you're really trying to achieve):
public int compute(List<Integer> result){
...
return result.size();
}
You can change the signature of the method to be public Object compute(), so that you can return both ArrayLists and Integers, but I'm not exactly sure why you'd want to do this.
It just means that whenever you call compute(), you're going to need to check the type of the Object that you received, e.g.
Object result = compute();
if(result instanceof ArrayList) {
// Do ArrayList stuff
} elseif(result instanceof Integer) {
// Do Integer stuff
}
Note: Object is the super class for all objects in Java, so if there is a time where you may want to return lots of different things, you can use Object. But the better solution may be to create an Interface, if the things you're returning will have something in common.
See here: http://docs.oracle.com/javase/tutorial/java/concepts/interface.html

java method to change the value of an array to null

public void setData(double[] d) {
if (d == null) {
data = new double[0];
} else {
data = new double[d.length];
for (int i = 0; i < d.length; i++)
data[i] = d[i];
}
}
this method in my code is used to set the data of an array. I am also required to write a method called reset() that changes a given array to have a null value. Also, we are practicing overloading in this lab. There are four versions of setData() (double, int, float, long). Since a double array is used internally by the Stat class to store the values, do I only have to make one reset() method of type double?(I think I only need one...) Finally, please give me some hints as to going about this reset business because everything I have tried has failed miserably and usually consists of statements such as
"setData(double[] null)" which return errors.
Everything in java is pass by value; even references are passed by value. So by passing an array through a method, you can change the contents of the array, but you cannot change what the array points to. Now, if you are inside a class and happen to pass an instance member that you already have access to by virtue of being in the class, you will be able to set the array to null.
If you always want to be able to change what an array points to, then simply have a function which returns an array (instead of being void), and assign that returned value to the array of interest.
Because java is pass by value, you can't reassign a variable passed as a parameter to a method, and expect to see that change reflected outside.
What you can do, is put the array in some sort of wrapper class like this:
class ArrayReference<T> {
T[] array; // T would be either Double, or Long, or Integer, or whatever
}
and then:
void setData(ArrayReference<Double> myReference) {
myReference.array = null;
}
I'm not sure if I understood your question, but is it that what you want?
public class Stat {
private double[] data;
public void reset() {
data = null;
}
public void setData(double[] d) {
data = (d == null) ? new double[0] : Arrays.copyOf(d, d.length);
}
}

Categories