I am trying to add object of type Shoe into the fixed array of type Shoe, but I have a problem with it.
In the addShoe method I am trying to add reference of type Shoe to the sh array like this: sh.add(s);
when I trie to run it I get this error:
Cannot invoke add(Shoe) on the array type Shoe[]
Eclipse recommends me to change it to 'length' and it doesn't make sens
I am also thinking I could write an else part of the addShoes method like this:
public void addShoe(Shoe s) throws ShoeException
{
if(s.getId() < 0) {
throw new ShoeException(s);
}
else {
if(numShoes<=10){
sh = Arrays.add(s, numShoes);
numShoes++;
}
}
}
It is just one of the ideas. Is it the correct way to do it?
public class TestShoe {
public static void main(String[] args) {
ShoeProcessor s = new Shoe();
Shoe s1 = new Shoe(7, "Black");
Shoe s2 = new Shoe(10, "Red");
try {
s.addShoe(s1);
s.addShoe(s2);
}catch(ShoeException bex){
System.out.println("Shoe Exception: " + bex);
}
}
}
public class ShoeProcessor
{
private Shoe [] sh;
private int numShoes=0;
private ShoeComparator<Shoe> sc;
public ShoeProcessor()
{
sh = new Shoe [10];
sc=new ShoeComparator<Shoe>();
}
public void addShoe(Shoe s) throws ShoeException
{
if(s.getId() < 0) {
throw new ShoeException(s);
}
else {
sh.add(s);
numShoes++;
}
}
}
Thank you for your help
I want to add I need to use array Shoe of fixed size.
I also want to add that I don't want to extend the array sh. I can add max 10 references of type Shoe to it. This is why I am also counting number of shoes added.
Probably I'm missing something: do you want replace sh.add(s); with sh[numShoes]= s; ?
Arrays in Java have a fixed size. You have two options:
Switch to using a List. This can dynamically grow when you add more items to it. For implementation you can use an ArrayList or LinkedList.
Try using System.arraycopy to resize your array each time you need to add to it. I don't recommend this. Internally, this is actually something that ArrayList does, but you are free to do it manually if you so choose.
edit: Just saw your edit. You can do something like:
public void addToList(Shoe shoe) {
if(shoeList.size() < 10) {
shoeList.add(shoe);
}
}
shoeArrayCount = 0;
public void addToArray(Shoe shoe) {
if(shoeArrayCount < 10) {
shoeArray[shoeArrayCount] = shoe;
shoeArrayCount++;
}
}
Depending on which method you choose to inplement.
Related
I'm having trouble understanding what exactly I would put in one of my classes to create the add method for 3 Arrays of the same Type. Here are the generic arrays in the main class
ArrayContainer<Integer> numberContainer = new ArrayContainer<>();
ArrayContainer<String> wordContainer = new ArrayContainer<>();
ArrayContainer<Pokemon> pokedex = new ArrayContainer<>();
My constructor for ArrayContainer is
public ArrayContainer(){
container = (T[]) new Object[defaultSize];
numItems = 0;
}
In my separate class, I'm confused what to put for my
public void add (T item){}
and I'm confused as what to return within my toString. I know you add to an array by putting
arrayName[index] = whatever;
But what would I put in that add method that would add to whatever array I call the method on? Would it be container[index] = item;?
What should I return that would return the element in the array?
Since the number of items in your ArrayContainer is not known beforehand, you should use a dynamic array, also known as List.
The numItems then becomes redundant since you can get it by calling list.size()
Your add function will only need to call list.add. As noted in the comments, it seems you're re-writing/wrapping List
In your toString method, you can return a string that concatenates all results of toString of the items included. StringBuilder can help you create a "format" that suits you. Of course this means that the objects you're putting in the container need to implement toString
Combining all the things will give you something like this:
ArrayContainer
public class ArrayContainer<T> {
private List<T> items;
public ArrayContainer() {
items = new ArrayList<>();
}
public void add(T item) {
items.add(item);
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[ ");
for (T it: items)
sb.append(it.toString()).append(' ');
sb.append(']');
return sb.toString();
}
}
Main
public class Main {
public static void main(String[] args) {
ArrayContainer<String> stringArrayContainer = new ArrayContainer<>();
stringArrayContainer.add("hello");
stringArrayContainer.add("world");
System.out.println(stringArrayContainer);
// Outputs: [hello world]
}
}
I need to be able to add a double value to an array list with a method. This is the one I created:
public void addPrice(double nPrice) {
if (nPrice >= 0) {
priceList.add(nPrice);
}
else {
priceList.add(null);
}
}
It is supposed to take the price that needs to be added as a parameter and not return anything. This price has to be at least 0. If the price is negative then nothing is done or added. I thought this would work but when I try the value 1.2 as my test dictates the value is not added to the least. Am I using the add operation wrong or is there something else I am missing?
I can't see all of your code so it's possible you're creating/accessing your ArrayList incorrectly.
ArrayList<Double> priceList = new ArrayList<>();
priceList.addPrice(1.2);
public void addPrice(double nPrice) {
if (nPrice >= 0) {
priceList.add(nPrice);
}
//Don't do anything if the price is not valid.
}
import java.util.ArrayList;
public class Tester{
public static void main(String[] args){
addPrice(1.2);
System.out.println(priceList.get(0));//this prints 1.2
}
/**
* Assuming you are using an arraylist like so.
* Remember to use a list you must use the class not
* just the primitive type.
*/
static ArrayList<Double> priceList = new ArrayList<>();
public static void addPrice(double nPrice) {
if (nPrice >= 0) {
priceList.add(nPrice);
}
else {
priceList.add(null);
}
}
}
How do you return an array object in Java? I have an object that has an array in it and I want to work with it in my main class:
// code that does not work
class obj()
{
String[] name;
public obj()
{
name = new string[3];
for (int i = 0; i < 3; i++)
{
name[i] = scan.nextLine();
}
}
public String[] getName()
{
return name;
}
}
public class maincl
{
public static void main (String[] args)
{
obj one = new obj();
system.out.println(one.getName());
}
I am sorry if the answer is simple but I am teaching myself to code and I have no idea how you would do this.
You have to use the toString method.
System.out.println(Arrays.toString(one.getName()));
toString is a built-in function in Java (it might need library import; if you are using Netbeans, it will suggest it).
If the problem is to print it use
System.out.println(Arrays.toString(one.getName()));
//note System, not system
When you do getName() you are returning a reference to an array of strings, not the strings themselves. In order to access the individual strings entered, you can use the array index
String enteredName = name[index] format.
From your program, it looks like you want to print each item entered. For that, you could use a method like the following
public void printName() {
// for each item in the list of time
for(String enteredName : name) {
// print that entry
System.out.println(enteredName);
}
}
I don't think i have the terminology correct, haven't been one for that. What i'm trying to do is get a string back , then use it to run functions. .. Example :
int slotNumber = ((j*3)+i+1);
String slotString = "slot"+slotNumber;
Regularly I can do this :
slot12.Draw();
And I want to be able to do this :
slotString.Draw();
With it substituting slotString with slot12 in a dynamic scenario. If i truly have to i could do something similar to :
if (slotString == slot1) slot1.Draw();
if (slotString == slot2) slot2.Draw();
And such, but i dont really want to use x number of lines for x number of slots.
Any help is appreciated :D
A possible solution would be to use a HashMap where the key is the slotNumber and the value points to the slot. Then you could do something like the following.
//Initialize at the start of your program
HashMap<int, Slot> SlotHash = new HashMap<int, Slot>();
//Code to retrieve slot and call Draw().
Slot select = SlotHash.get(slotNumber);
select.Draw();
Maybe use a Map if your slots are sparsely-packed. If they're densely-packed, you might be able to use an array of slots. In either case, you do the slot lookup based on index and then call Draw on the looked-up slot.
You would have something like this:
Slot slot1 = new Slot("slot1");
Slot slot2 = new Slot("slot2");
SlotController controller = new SlotController();
controller.add(slot1);controller.add(slot2);
String someSlotNumber = ".....";
controller.draw(someSlotNumber);
See the definition of the classes below:
class SlotController {
Map<String, Slot> slotMap = new HashMap<String, Slot>();
public void addSlot(Slot aSlot) {
slotMap.put(aSlot.getSlotName(), aSlot);
}
public void draw(String slotName) {
slotMap.get(slotName).draw();
}
}
class Slot {
private String slotName;
public Slot(String name){
slotName = name;
}
public String getSlotName() {
return slotName;
}
public void draw() {
}
}
Ok, here is the code and then the discussion follows:
public class FlatArrayList {
private static ArrayList<TestWrapperObject> probModel = new ArrayList<TestWrapperObject>();
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] currentRow = new int[10];
int counter = 0;
while (true) {
for (int i = 0; i < 10; i++) {
currentRow[i] = probModel.size();
}
TestWrapperObject currentWO = new TestWrapperObject(currentRow);
probModel.add(counter, currentWO);
TestWrapperObject testWO = probModel.get(counter);
// System.out.println(testWO);
counter++;
if (probModel.size() == 10) break;
}
// Output the whole ArrayList
for (TestWrapperObject wo:probModel) {
int [] currentTestRow = wo.getCurrentRow();
}
}
}
public class TestWrapperObject {
private int [] currentRow;
public void setCurrentRow(int [] currentRow) {
this.currentRow = currentRow;
}
public int [] getCurrentRow() {
return this.currentRow;
}
public TestWrapperObject(int [] currentRow) {
this.currentRow = currentRow;
}
}
What is the above code supposed to do? What I am trying to do is load an array as a member of some wrapper object (TestWrapperObject in our case). When I get out of the loop,
the probModel ArrayList has the number of elements it is supposed to have but all have the same value of the last element (an array of size 10 with each item equal to 9). This is not the case inside the loop. If you perform the same "experiment" with a primitive int value everything works fine. Am I missing something myself regarding arrays as object members? Or did I just encounter a Java bug? I am using Java 6.
You are only creating one instance of the currentRow array. Move that inside the row loop and it should behave more like you expect.
Specifically, the assignment in setCurrentRow does not create a copy of the object, but only assigns the reference. So each copy of your wrapper object will hold a reference to the same int[] array. Changing the values in that array will make the values appear to change for all other wrapper objects that hold a reference to the same instance of the array.
i don' t want to sound condescending, but always try to remember tip #26 from the excellent pragmatic programmer book
select isn't broken
it is very rare to find a java bug. keeping this in mind often helps me to look over my code again, turn it around, and shake out the loose bits until i finally discover where i was wrong. of course asking for help early enough is very encouraged, too :)