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.
Related
I'm trying to figure out how to assign multiple variables to int type but I'm not sure how to assign it to them. Also, I'm having difficulty understanding how you can use a boolean with this restriction. I was thinking about putting them in an array but I'm not sure if there is an easier approach to the problem. Any help is much appreciated!
Instructions for Attraction.java
Write a Java program Attraction.java that has the following characteristics.
extends Place
New attributes: type (int) price (double)
New Methods: public Attraction(String name, String desc, double latitude, double longitude, double price, int type) where for type values:
0 is an amusement park
1 is an aquarium
2 is a zoo
public double getPrice() -- returns current price
public int getType() -- returns type
public boolean hasAnimals() -- returns true if type contains "zoo" or "aquarium"
Your hasAnimals method needs to return a boolean value i.e. true or false based on the value of the type variable.
You're .. kind of on the right track, but you're not honoring the requirements of the method. It shouldn't print anything, and it shouldn't return type because type is an int and not the boolean that is required.
public boolean hasAnimals() {
if(type == 1) {
return true; // aquarium has animals
} else if (type == 2) {
return true; // zoo has animals
} else {
return false;
}
}
Think carefully about what a method is called, and what it should do. This method is just a way to answer a yes/no question.
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
Beginner, can't seem to wrap my head around this.
Item Class
public class Item implements Comparable {
private int number;
private String description;
public Item(int num, String descript){
this.number = num;
this.description = descript;
}
public int getNumber(){
return number;
}
public String getDescription(){
return description;
}
#Override public int compareTo(Object o){
Item i = (Item) o;
if(this.getNumber() < i.getNumber())
return -1;
if(this.getNumber() > i.getNumber())
return 1;
return 0;
}
}
Main method
Item[] items = new Item[3];
items[0] = new Item(102, "Duct Tape");
items[1] = new Item(103, "Bailing wire");
items[2] = new Item(101, "Chewing Gum");
Arrays.sort(items);
for (Item i : items){
System.out.println(i.getNumber() + ": " + i.getDescription());
}
When the main method instantiate items[0] = new Item(102, "Duct Tape"); Which goes through Item constructor to set current variable number, description.
My problem is I can't seem to understand what is being passed in the compareTo argument, therefore I can't seem to understand this.getNumber() < i.getNumber() is doing...
Return a negative number if current object is less than passed object?
any help is much appreciated.
The raw interface Comparable that you are using allows this object to be comparable to another Object. It is then cast to Item to ensure that the this Item is only compared to another Item.
According to the Comparable Javadocs,
Compares this object with the specified object for order. Returns a
negative integer, zero, or a positive integer as this object is less
than, equal to, or greater than the specified object.
Additionally, your compareTo will throw a ClassCastException at runtime if the Object isn't an Item.
It's better to use the generic form of the interface:
public class Item implements Comparable<Item> {
Then you can specify Item instead of Object to compare against:
#Override public int compareTo(Item i){
and you don't have to cast the Object to an Item. When calling compareTo, the compiler will enforce that the object to compare to must be an Item.
My problem is I can't seem to understand what is being passed in the compareTo argument
Array.sort uses the compareTo method to know how to compare pairs of items from the array.
Your sort method assumes that it will only be called with instances of Item, and that's all Array.sort will pass along to compareTo assuming that your array only holds instances of Item.
You will get a runtime exception if compareTo is ever invoked with the item being compared to not being an instance of Item.
I can't seem to understand this.getNumber() < i.getNumber() is doing...
It's comparing two instance of Item based on the value of getNumber, that is, the value of their number fields. It assumes that two instances of Item are equal if Item.number is the same for each instance, otherwise one is less than the other if its Item.number is less than the other's Item.number.
You are trying to override the default compareTo() method, which takes in a single Object as a parameter. Thus, in your implementation, the parameter needs to be of type Object. However, you assume that you will be passing in a Item object, so you can cast it accordingly.
So in the end, your Item object is treated like an Object, which is casted back to an Item in your compareTo() method.
The Object being passed to your compareTo method is an Item object. The Arrays.sort() calls the Overrided method method when you have it implemented, the best implementation is to return the compareTo method for the primitive java types
#Override
public int compareTo(Object o){
return (this.getNumber().compareTo((Item)o.getNumber());
}
(this requires you to have number as type Integer though)
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.
For example, I have a method that looks through a string for data separated by a specified deliminator, but some items might be a names, and other items might be numbers.
If a user calls my method to return item number X from the deliminated list, i want it to return a string if item X is a name, or a double if item X is a number.
For example, objectName.get(5); would get the 5th item in the deliminated list.
Would I have to use some type of overloading for this?
Or would I have to instead do something like objectName.getDouble(5); and objectName.getString(5); based on the fact that the user knows what item 5 is?
But what if the user doesn't know what item 5 is? He just needs a String or a Double depending on what it happens to be.
Here's one way to do this:
public Object get() {
if (blueMoon) {
return new Double(42.0);
} else {
return "fred";
}
}
Note that this will return a Double wrapper rather than a double.
I don't think this is a good idea though, since the caller now has to test the type of the returned value and do a typecast to do something with it.
For the record, Java does not allow a method to return a String or double because these types do not have a common supertype in the Java type system.
For this sort of thing, I prefer to use something akin to the Maybe/Option pattern from the functional programming camp. You end up with an interface like:
public abstract class DoubleOrString
{
// Constraint isDouble() xor isString()
public boolean isDouble();
public boolean isString();
//Must throw iff !isString()
public String getString();
//Must throw iff !ifDouble()
public Double getDouble();
public static DoubleOrString wrap(final double wrapMe)
{
return new DoubleOrString()
{
public boolean isDouble() {return true;}
public boolean isString() {return false;}
public Double getDouble() {return wrapMe;}
public String getString() {throw new RuntimeException();}
};
}
//same for wrap(String)
}
This forces the issue for clients, in that there is always a sanity check that there was indeed a double or String at the appropriate time. In your case, I'd make just one get() method, so when the client (thinks they) knows what the type is, the call is
objectName.get(5).getString();
and in your get(int) method, rather than returning a String or a double, the return statement looks like
DoubleOrString.wrap(theThingToReturn)
It's a little extra work up front, but it has paid of for me several times in the past.
Here's how you'd use it to build one (warning - this hasn't been near a compiler)
public static DoubleOrString parseADoubleOrString(String input) {
try {
return DoubleOrString.wrap(Integer.parseInt(input))
} catch (NumberFormatException nfe) {
return DoubleOrString.wrap(input);
}
}
and here's what the client looks like
String input = //get the input from the user somehow
DoubleOrString parsed = parseADoubleOrString(input);
if (parsed.isDouble())
aFunctionThatTakesADouble(parsed.getDouble());
else
aFunctionThatTakesAString(parsed.getString());
If you need to do this then there is problem with your design. Since the original datasource is String you have to accept that all returned values will be string and leave it to the client to check whether the result can be converted to a number.
If you want to save the client from doing the check, you can provide him with a minimal API which may look something like:
public class ValueExtractor {
public ValueExtractor(String delimitedText) {
// ...
}
/**
* Determines whether there is a next element
* to be returned
*/
public boolean next() {
// ...
}
public String get() {
// ...
}
/**
* Returns the value as a Double if possible
* null otherwise.
*/
public Double getPossibleDouble() {
// ...
}
}
The Java language does not expose an overload on the return type of a method. (As Thilo pointed out, this is a restriction of the Java language and not the JVM/bytecode.)
Generally this type of thing does not fit well into the Java type system. One could imagine returning an Either<String,Double> type (a more restricted return type than Object as suggested by Stephen C and a more general type than DoubleOrString as pointed out by B. Bear), but the general effort required to use such a construct in Java generally results in simply having multiple methods, e.g. getString(...) and getDouble(...).