Dynamically Add Objects To Array In Any Position In Java
Feb 6, 2015
I have an assignment in which I have to design a method where I add an object at any given position in an array and shift the elements already in the array to make room. For example I have a collection class which holds trading card objects. So I wish to add a new trading card to this collection at a specified index or position with out deleting the current object already stored in the array . All this has to be done without the use of array lists, vectors or any abstract data types besides arrays . My question is how do I accomplish this . Say I wish to add a new trading card in position 4 the new card is added to my array and the card currently in position 4 gets moved to position 5 and the card in position 5 gets moved to 6 etc. The maximum amount of cards my collection can hold is 100. How would I add my trading card object to the specified position without overwriting what is currently there and shifting all other elements?Here is my current code.
public class CardCollection {
public BaseballCard [] collection;
final int MAX_CARDS = 100;
public CardCollection() {
collection = new BaseballCard[MAX_CARDS];
}
public CardCollection(BaseballCard[]c)
[code]...
position refers to the position in the CardCollection and not the position inside the array.
I can't recolate and align the button, the circle or the line where i want it to on the canvas. I want to be able to move the line where i want it, now it seems like all objects are stuck in the middle of the scene or canvas.
I am trying to draw add flowers on a graphics window. I can do this just fine, however the position starts from the far left and goes to the far right. I would like to position the 8 flowers in the center of the screen but can't seem to get the right formula to do so. Here is what I have so far to draw the flower, which is simply a GOval nothing complex:
The box size of the window is 800 by 600. Ideally I would like to place x amount of flowers spread across the middle of the screen. How might I do this???
'm working on a program that is to act as an inventory for a book store. There are two classes (Store and Book), and numerous methods which you will see in my code. The program is supposed to read in an inventory from a file which contains 10 books (each row in the file represents a book with an ISBN number, the price of the book, and the number in stock)and store this file into an array of type Book[]. There is then to be another method to process a purchase interactively. The Store class is also to keep a count of how many books were sold at the time of closing and also how much was made that day.
I'm having some difficulty figuring out how I should set up the purchase processing method though. I've written out how I think it would be set up (not too familiar with the terminology, but I think it would be called pseudo code?) I'll include that now along with a few other notes.
public Book[] purchase(String isbn, double price, int copies) { int itemsSold; double totalMade; Scanner input = new Scanner(System.in); System.out.println("Please enter the ISBN number of the book you would like to purchase: ");
[Code] ....
So basically here's what needs to be accomplished with this portion of code:
1.Ask the user to enter the ISBN number of the book they'd like to purchase. 2.Search the array for the object that contains that ISBN. 3.If the ISBN isn't found in the array, display a message stating that we don't have that book. 4.If the ISBN is found but the number of copies is 0, display a message saying the book is out of stock. 5.If the ISBN is found and the number of copies is greater than 0, ask the user how many copies they'd like to purchase. 6.If the number they enter is greater than the number of copies of that book in the array, display a message stating that and ask them to enter another quantity. 7.Once the purchase is complete I need to update the array by subtracting the number of copies of that particular book that was purchased. 8.Print the updated array. 9.Display a count of how many books were purchased, and how much money was made from the purchase.
I know that code has a lot of holes in it, but I'm just trying to get everything together and figure out how to do each step.
The part I'm stuck on right now is trying to figure out how to search the array to first see if the ISBN that was entered is in the array, and then to find the number of copies of the book with that ISBN number.
In case it will visualize what this array looks like, here's a print out of the array from a sample run I just did.
I want to take my 5x5 array that reads data from a file, add the rows and columns, then print out a new 6x6 array with those values. Here is my code that shows I understand everything except this.
import java.io.*; import java.util.*; public class prog470cAddingRandC { public static void main (String [] args) { //read the file Scanner inFile=null;
[Code] ....
I was told in a previous question to make the starting array 6x6 but that is not working. How do I take sum1 and sum2 and store that along with the values of the old array and print it?
I'm having trouble conceptualizing something. I will post the code, it's works exactly as it should. I create an array and Hash Map to display periodic table of elements information after allowing the user to search by element name or symbol. I want the user to also be able to add elements to the periodic table. I can't really conceptualize how I am going to do that with an array I've already created.
Here's code:
//Create element objects. //Here is where I create my "elements" array, and where I could like to prompt the user to add elements, if desicred. Element[] elements = {new Element("Hydrogen", 1, "H", 1.008,1,1), new Element("Lithium",3, "Li", 6.94,2,1)}; // //Maybe it seems if I prompt the user here to add new element names, symbols, weights, etc, I would be overwriting
1) I'm trying to use a logarithm to determine the length of a user input number. I keep getting an error stating <> indetifier expected. I'm assuming this means that the program is not recognizing the function of a logarithm. I know that normally you can include that information in the method, but my teacher has stated specifically that each of these methods be called something else, as shown in the code.
2) I'm not quite sure I understand how to assign the numbers I obtain from the modular equation to a certain position in the array. As I'm asking the user to input any number these values can change so therefore I can't simply state that first number = this place.Here is my code:
import javax.swing.*; import javax.*; public class getSize { public static void main( String[] args )
I am learning about arrays in my class and my professor has a habit of throwing in code without explaining. We are doing a program called storing largest numbers where we read data from a file and place the larger of the two numbers in the corresponding position of a third array. They are in 4 by 4 format. Here is the ending code
import java.io.*; import java.util.*; public class prog464aStoringLargestNums { public static void main(String[] args)
I'm working on a lab for my class. I need to create a Priority Queue in Java using an array list. The kicker is that each node has to have a "handle" which is just an object which contains the index of of the node that it's associated with. I know that sounds weird but we have to implement it this way. Anyway, my priority queue seem to work fine except the handle values apparently aren't updating correctly because I fail the handle test. Also, I run into problems with handles only after extractMin() is called, so I figured the problem would be somewhere in that method but I've been through it a million times and it looks good to me.
Here is my Priority Queue Class:
package lab3; import java.util.ArrayList; /** * A priority queue class supporting operations needed for * Dijkstra's algorithm. */ class PriorityQueue<T> { final static int INF = 1000000000; ArrayList<PQNode<T>> queue;
[Code] ....
I can post the tests too but I don't know if that would do much good. Just know that the queue works as is should, but the handles don't point to the right nodes after extractMin() is utilized.
I need to generate the word document dynamically using java code, included the necessary jar files, No compliation issue, but During run time am getting this error: Could not initialize class org.openxmlformats.schemas.wordprocessingml.x2006. main.CTDocume .using all these jar files: POI-3.6.jar, POI_3.9.jar, Poi-ooxml-3.5,Poi-ooxml-3.6,Poi-ooxml-3.7,Poi-ooxml-3.9,Poi-ooxml-schemas-3.6,Poi-ooxml-schemas-3.9.jar. using the XWPFdocument class. when my cursor get into that line XWPFDocument doc = new XWPFDocument(); getting the above error.
I am working on a program that asks me to track the position of an imaginary ball as it bounces around an imaginary box. The user gives me input for the starting position of the ball (x,y), the bottom-left boundaries of the box (xl, yl), the top right boundaries (xr, yr) and the angle. The program then needs to find where the ball will hit the box, and then print that location and find the new angle for the next point. My program currently works in most cases if the angle is less than pi.
Here is my code
public class BouncyBall { public static void main(String args[]){ if (args.length != 8) { System.out.println("Error: usage is X, Y, Angle, Xl, Yl, Xr, Yr,N"); System.exit(1); } double x,y,xl,yl,xr,yr,angle; int n; x=Double.parseDouble(args[0]); y=Double.parseDouble(args[1]);
Exercise the Coin class using a driver class in which 5 coins are flipped, as a group, 1024 times. Display the number of times exactly 4 tails are obtained. Display the number of times exactly 5 tails are obtained. Use an array of Coin.
how to put an object into an array?I know how to make a coin class with a Heads and Tails, but I dont know how to make 5 coins all at once.
I know the first line below creates an object but the second line creates an array of cars, I'm just not sure how it does that. I can see sportsCar is one object in the array but the others are written in a different way. It seems there should a couple names there instead. Please explain the syntax in this code that's highlighted. I don't know how to make sense of it and I've read through the book where I got it where it explained creating objects.
Auto sportsCar = new Auto("Ferrari", 0, 0.0); Auto [] cars = {new auto("BMW", 100, 15.0), sportsCar, new Auto()};
I have a list of objects in my bean (ex: List<Apple> applies = new ArrayList<Apple>() ).The object has several fields (ex: supplier, color, width, height, breadth, etc.)I want to show this list on the front end. However I also want to allow the user to edit the attributes of the apples.So from the front end I will have like a list of fields where a set of fields is related to a single object in the list.I would also like to add/delete apples.
What first came to my mind is to map every field in the object Apple to a List. For example if Apple has field suppliers and field color then in the bean I would create two Lists, List<String> supplier, and List<String> color.From the front end I would display the contents of these Lists rather then the List<Apple> apples.T
he name of the field would be the same for each set of attributes.On save (form submit) the Lists would be re-populated with the field values (changed or not) and then I would be my Apple objects from the bean before saving in database.However I am not sure if there is something in JSF that can achieve this in a simple way, working only with List<Apple> rather than adding additional Lists.
okay,I created a program that demonstrated an array holding a number of objects, each from different classes.the printout I got for the first program ended up being gibberish. when I made the program a second time, I got the correct result.I've been trying to pinpoint the anomaly but I can't seem to find it. So ill try breaking down what I did?
Goal:The purpose of the program was to have a single Class (we'll call the Class 'Animal') to pass the parameters of a previously made method. This method would, amongst other things, call on an array.Further, I would then make subclasses of the Class Animal, and then use them as well to pass the method parameters, thus demonstrating subclasses can be used in place of the super class.
3 of these classes were made purely to as a "place setter". the Classes called "Cat" and "Dog" respectively were created to be subclasses of the Class Animal (with no other code inside them aside from "extends Animal)the 3rd "place setter" called "ClasstoHoldObjects" was created to be the array class (ClasstoHoldObjects itself has no code in it aside from the class name)these are the ones we want.Animal class (which holds the coding meant to be used).Here is the Animal Class
public class Animal { private ClasstoHoldObjects[] thelist = new ClasstoHoldObjects[5]; int i = 0; public void add(ClasstoHoldObjects x){ if(i < thelist.length){
[code]....
the print out was this next, im putting THIS line in the array... june_6.Dog@a0dcd9 (and the same by the Cat object).I recognize june6 as the package name.
finally, I erased extra lines as well as comments and simplified class names to make the code more readable. If you want the original, or some class names are a bit off- I could give you the original with all its comments and longer named classes
I have a program I want to make (text based, no gui). There is the main class, an Employee class (sort of a template), a CrewMember class, and a Manager class.
I'll put the code for each class an explain the problem I have.
package polymorphism; import java.util.Random; public class Start { public static void main(String[] args) { Random rand = new Random(); Employee staff[] = new Employee[5]; for(int i = 0; i < staff.length; i++){
[Code] ....
Some of the code is a bit incomplete simply because I ran into the problem. As you can see I made an array in the Start class and it holds objects of Employee type, but create a new instance of either a crew member or a manager, sets their wages, hours, and bonus if applicable. I know if I create an array of a certain type, I can't call upon the subclass' method (Manager in this case) because it has a new method that I added. What I'm trying to do is pretty much call upon the getSalary() method in the Manager class/object, but of course I can't. What way would i be able to do that? I tried looking for some answers. I read about making the superclass abstract and implementing it into the subclasses. Would that be an option?
An array has objects with String firstName, String lastName, int ID, char examType('M' or 'F'), and int score. Every object has both Midterm('M') and Final('F'). The array has to be sorted by the first Midterm- 'M' and immediately followed by the Final ('F') of the same person (object). Im having troubles with coming up with a proper algorithm with gettin the Final- 'F' after Midterm for the same person.
Java Code: public static Exam[] collateExams(Exam[] exams) { Exam [] r = new Exam[10]; r = exams; int[] position = new int[10]; int index = 0; for(int i = 0; i < exams.length; i++)
I have an assignment where I need to add an interface to an already-created program. I have an array of objects, where each object has a name, price, and priority.
In my original program (which worked), I had all of the objects in 1 class. The professor said that I should split up the name/price/priority into 3 different classes. So what I have is an array that belongs to an interface, and name/price/priority implements. But I am having trouble loading the data into the array (from another class) once I am done with loading name.
Here is what I have so far.
public class Main { public static void main (String[] args){ Interface[] arr = new Interface[7]; Scanner keyboard = new Scanner(System.in); System.out.println
[code]....
Line 18 in the ItemName class is giving me an error, and I know it is because arr is of type Interface, and I am trying to assign is a String. But I don't know how to do this. In my original program I was able to do arr[x].getName(); but when I do that in Main, I get errors.
how to assign to an interface array from multiple classes.
if, instead of an ArrayList, can I do the following to initialize a Dyanmic array ? :
First, in my class, I have :
class Example{ private int rows; private int columns; private AnotherClass[][] 2DArray; public Example(int rows, int columns){ this.rows = rows; this.columns = columns;
I want to keep count of how many students are in my array. the array i made up of objects from other classes. like the class Student how do i do this. i have tried contains but better way it to to a loop to go through the array and determine if each object is a particular type but i don't know how to do this. here is the code
import java.util.*; import java.util.ArrayList; public class Driver { public static void main(String[] args){ /* Comments required PersonFileReader pfr = new PersonFileReader("person.dat"); ArrayList<Person> testData = pfr.readData(); Database db = new Database(testData);
I want to create a simple app that takes a name from the console then compares the name to a small phone book,when the name matches another name it will return the associated phone number.
I have a small contacts class which has name and number fields,Then I have a phone book class which populates an array with 4 contact objects that I can compare the entered number against.
here is my contacts class
public class Contact { String name; int number;
[Code].....
In the main method I am just trying to print out one of the fields for one contact to see if I can actually access it to compare it to the name entered.Its saying "MaryJones" cannot be resolved to a type.I'm guessing I cant create all that code in the constructor?
I am trying to build a method that takes an array of object and adds a new object of that type to the end of it . ONLY ALLOWED TO USE ARRAY , NO ARRAYLISTS VECTORS ECT . i realize that if the array is full you can use the java copy array method to make a new array and double its size until a certain point . The MAX AMOUNT OF OBJECTS is a constant that is 100 but for some reason even when executing my code i keep getting null pointer exceptions or index out of bounds errors , i have written this method many times now with out any success.
My question is how do I write a method that adds an object to the end of an array and if there are no spots left copies the current array into a new array and extend the size
private Animal [] objects; final int MAX_ANIMALS = 100; public AnimalObject() { objects = new AnimalObject[MAX_ANIMALS]; } public AnimalObject(Animal[]a)