Extending an array multiple times - Help!
Hi everyone,
I am very new to Java (doing my first class now) and I need some help with making an array larger. I have written a program that will display a list of products created in a static array. The program needs to include an "add" button, that will prompt for new product information, and add it to the array.
I've managed to get this coded up to a point where my add button works (albeit only is adding product name at this point...will add the rest later once this works). The problem is, when I attempt to run the add button a second time, it does not grow out the length of the array. The result is that it updates the last record within the array with the new product information, rather than appending a new one. Here is the code I think is relevant (as I don't think you are allowed to entirely post school work):
// Assignment: Inventory Program Part 6
// Author: Ryan MacDonald
// Class uses both swing and awt components, also using number format for currency, and AWT events
import javax.swing.*;
import java.awt.*;
import java.text.NumberFormat;
import java.awt.event.*;
// InventoryPart4 class
public class InventoryPart6
// Declare array of products
static Product_Extender Item[] = new Product_Extender[4];
// snip
// snip
// Main method
public static void main ( String args[] )
// Create a new product object
Item[0] = new Product_Extender( 1, "Pink Markers", "Pentel", 31, 0.61 );
Item[1] = new Product_Extender( 2, "Blue Pens", "Bic", 57, 0.30 );
Item[2] = new Product_Extender( 3, "Red Markers", "Zebra", 62, 0.55 );
Item[3] = new Product_Extender( 4, "Black Pens", "Bic", 73, 0.33 );
// snip
// snip
// Make add button work
addAddButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Product_Extender newItem[] = new Product_Extender[Item.length + 1];
System.arraycopy(Item, 0, newItem, 0, Item.length);
newItem[newItem.length - 1] = new Product_Extender( newItem.length, productNameText.getText(), "Test New Item", 99, 0.99 );
Product_Extender Item[] = new Product_Extender[newItem.length];
System.arraycopy(newItem, 0, Item, 0, newItem.length);
// Update main text area with our new product information
mainText.setBorder(BorderFactory.createTitledBorder("Product Inventory (All Items)")); // Create a title around the textarea with some text
mainText.setText( String.format("Product #" + "\t" + "Name" + "\t" + "Manufacturer" + "\t" + "Quantity" + "\t" + "Price" + "\t" + "Value" + "\t" + "Restocking Fee" + "\n") ); // Create a line of text with the product header information
// Loop through each item in the product array and append the information to the main text area for the product number, product name, quantity in stock, price per unit, total value of inventory, and restocking fee for this item
for(int i = 0; i < Item.length; i++) {
mainText.append(String.format(Item.getProductNumber() + "\t" + Item[i].getProductName() + "\t" + Item[i].getProductManufacturer() + "\t" + Item[i].getProductQuantity() + "\t" + NumberFormat.getCurrencyInstance().format(Item[i].getProductPrice()) + "\t" + NumberFormat.getCurrencyInstance().format(Item[i].getInventoryValue()) + "\t" + NumberFormat.getCurrencyInstance().format(Item[i].getRestockingFee()) + "\n" ) );
// Set array location
currentLoc = -1;
// Close window
addFrame.dispose();
// snip
// snip
} // End method main
} // End class InventoryPart6
Basically here is my train of thought (although my logic could be ENTIRELY off, I'm very new here...). From what I've read, there is no way to actually grow/extend an array. The only option is to create a new one and populate it with the same data.
1. Since I can't grow it, I make a new array called "newItem" with Item.lengh + 1 as it's size
2. I then copy the contents of Item over to newItem
3. Since I need Item later, I recreate it with a new size of newItem.length
4. Copy the data from newItem over to Item
5. Print out the data from Item back to the main text area
What I would like to do is rinse and repeat this process as many times as the user would like. However as I said, it doesn't seem to work. Each time it reiterates again, it sets Item.length back to 4, not having it grow each time (deduced this by adding a bunch of prints of variables to my window).
Any help would be appreciated!!!
nvrmore100 wrote:
I actually have a lot of other buttons that manipulate the displaying of the array in various ways. I thought about creating a much larger array, but this would break all the functionality I have for displaying next, previous, last, items in the array.Then your functionality is incorrect. You should have a variable that keeps track of how many items are stored in the array. This will always allow you to access the last element. And when this variable reaches the size of the array only then do you increase the size of the array.
I agree, I think this is exactly my issue, unfortunately I do not know where to go from here. Is there a way for me to recreate the Item array entirely, rather than having a local array to the addbutton action method?I already showed you how to fix your problem. Delete your line of code and replace it with mine.
Similar Messages
-
so ive tried to redownload the iso5 for my ipad two multiple times over the last few weeks, and it simply isnt working, and to add insult to injury ive just purchaced some new apps from the appstore that cost £6 each, and they require the iso5 softwear :'( i need the apps to complete my exam coursework which is due very soon. please please help
You could try downloading the update via a browser instead : https://discussions.apple.com/message/16703914#16703914
-
When I double click on an image (from Bridge for example) to open in Photoshop it will open up CS6 and then sometimes when I open another image, instead of opening up in the same open Photoshop program, it will open up an additional Photoshop program. Both CS6, Version 13.0.6 x64. Super frustrating when sitting with a client and trying to add an image to a document and it opens up in a different program... Is there a way to see where Photoshop is opening from? Why would CS6 be opening multiple times???
I don't think I noticed this happening before I upgraded to Mavericks (yes, this has been happening for a while). I also have a back-up program called SuperDuper that mirrors my system on a separate hard drive. Could Photoshop be opening from there, too?
Thanks for any possible help!
DeronUse Lion Recovery to reinstall the Mac OS X.
-
I am having a big problem. I am not getting notifications from snapchat and only snapchat. I've made sure every notification setting was on and it just won't work. I have also restored my phone and deleted the app and re-downloaded it multiple times. It just wont give me my notifications. Help please.
Go to Settings > Privacy > Location Services.
Turn off SnapChat.
Go to Settings > Notification Center
Turn off SnapChat.
Restart the device.
Go to Settings > Privacy > Location Services.
Turn on SnapChat.
Go to Settings > Notification Center
Turn on SnapChat.
Test the issue. -
I recently tried to update iTunes to 11.1, and am now getting an error message "This application has failed to start because MSVCR80.dll was not found. Reinstalling the application may fix this problem." I have uninstalled and reinstalled iTunes several times with no success. I am running Windows XP Svc Pack 3. Help please.
Click here and follow the instructions. You may need to completely remove and reinstall iTunes and all related components, or run the process multiple times; this won't normally affect its library, but that should be backed up anyway.
(99753) -
flash player has been installed multiple time without errors but bbc news website and even flash player help say it isn't. How do i get out of this loop? - using windows 7 ultimate and latest IE11
I have had the same problem for WEEKS and I cannot access any sites that use Flash. Flash has been installed on this computer since I bought it in 2012. I have allowed auto updates but for weeks the updates never get past Step 2 - is this because I do NOT want the Google Tool bar? I use NO tool bars as there is only 6 inches of vertical screen space. Is this because I uncheck wanting Chrome as a default browser? It is already installed, I just don't use it. I came to this site and ran the check is it installed and the system says it is either not installed or not enabled. Version 14 just downloaded about 30 minutes ago - but did not progress to Step 3 although a pop up screen came up with a finish button, which I clicked. WHAT is the problem and how do I fix it? If this were just a compatibility bug between IE11 and Adobe they have had plenty of time to fix it.
Stephanie HC -
I took my iPhone running today and when I returned I was not able to slide it open or type in my pass code. All buttons are still responding. I have tried restarting it multiple times and even restored it, but the touch screen will not respond to anything. I also cleaned the screen off with a damp cloth. Please help! I WAS able to slide it open in the middle of restoring it but not able to click on any apps. Help! My life is on my iPhone and I am a nurse on call!
Try restore as new using computer iTunes.
-
When I enter my password to start my atv it tells me, that "there was a problem connecting to the network." My Ipad works fine in my house, but not my new atv. I have reset my password multiple times with no help. I have also rebooted my wireless server. Do I take it back?
Where is everyone???? Does anyone have an answer???
Allik1 -
I have an iPod Classic 160GB and now it will not sync. I have restored to factory settings multiple times. It freezes during sync, gives -50 error code and says video is not supported on iPod. Please help.
This is the iPod touch forum. I requested the moderators to move your post to the iPod classic forum.
-
using SharePoint 2010 > under marketing > task, user getting kicked out of share point multiple times. don't know the reason, does any one have any idea, learning about SP, any help will be appreciated.
try this one:
http://sharepointsolutions.blogspot.com/2008/06/how-do-i-make-our-sharepoint-site-stop_17.html
if fixed the issue fine other wise could you please check the ULS logs/ application ?IIS logs at the same time user kicked out.
Please remember to mark your question as answered &Vote helpful,if this solves/helps your problem. ****************************************************************************************** Thanks -WS MCITP(SharePoint 2010, 2013) Blog: http://wscheema.com/blog -
Need Help, i have an Ipad2 after 6.3.1 update, i have no cameras, or e-mail, I already reset, multiple times, but no improvment, can anyone help?
When you say reset, do you mean a reboot by holding both the power and home buttons until the apple logo appears, ignoring the red slider if it appears?
-
I made a card using the iPhoto and when I click to buy it, it says that I did not fill all the frames with pictures and that I need to in order to purchase it, even though I did and have checked multiple times. Please help, it's for Mother's Day.
Before ordering your book preview it using this method - http://support.apple.com/kb/HT1040 - and save the resulting PDF for reference - the delivered book will match it.
LN -
I have a fairly new iPod touch and the touch screen has suddenly stopped working..... Like the bottom row of apps has stopped working and certain buttons on the keypad are not working at all what so ever I have taken it to the apple store once before they told me to update it I did so and it didn't get better I have also restored it multiple times still nothing I really would like a working I pod please help!!!
If you restored to factory settings/new iPod and still have the problem that indicates a hardware problem.
Make an appointment at the Genius Bar of an Apple store..
Apple Retail Store - Genius Bar -
This is not working for me. I tried the Windows 7 Resolution steps multiple times to no avail. Please help. I am obviously connected to the internet (as is iTunes Store).
I am connected to the internet through a Verizon Wireless card, that is my regular internet connection.I did all that HT1925 recommended and it was no help. My computer still won't recognize my iPhone. Often trying to start Apple Mobile Device Service fails with an error message that it starts and then stops immediately.
-
Help writing HTML formatted data to JEditorPane multiple times
I have problems writing data to a JEditorPane more than once. The first time, it works, but the 2nd, 3rd, and so on, the data that is displayed is corrupt. This is where I print the data:
ResultsDisplay.getEditorKit().createDefaultDocument();
ResultsDisplay.setText(inputStore.toString());There seems to be something wrong with the way I display the data. What do I have to do to change HTML formated data that is printed to an JEditorPane?
This is how I set up the JEditorPane:
javax.swing.JEditorPane ResultsDisplay = new javax.swing.JEditorPane();
JScrollPane ResultsDisplayScrollPlane = new JScrollPane(ResultsDisplay);
HTMLEditorKit htmlEdKit = new HTMLEditorKit();and
ResultsDisplay.setEditable(false);
ResultsDisplay.setEditorKit(htmlEdKit);
ResultsDisplay.setContentType("text/html");
ResultsDisplay.setEditorKitForContentType("text/html", htmlEdKit);
getContentPane().add(ResultsDisplayScrollPlane);
ResultsDisplayScrollPlane.setBounds(50,50,700,450);Am I doing anything wrong here? Why can I only write the data once during the Applet's run life?Hi again,
Does anyone have experience writing to a JEditorPane multiple times during the run-life of a Applet? When I first send the data, it is displayed correctly. But everytime after that, the data is corrupted. My data is written in tables (in HTML format). The second time I write to the JEditorPane, it only displays the first of my tables, and only displays the collumn names and in the last column it displays the first row of data squeezed into the last column name's cell. If I run a third time, it takes this old table and adds a new table from the third run. With the fourth run I end up with 3 tables each containing only one row with the column names and the 1st row of data squeezed into the last collumn name cell.
Can anyone help? I've already tried creating a new document as described in the JEditorPane's API.
Maybe you are looking for
-
Multiple websites, multiple woes: Best IWeb 09/MobileMe strategy?
I'm still a bit confused as to the best strategy for using IWeb 09's much-touted-in-reviews but apparently rather limited ability to publish to two or more separate MobileMe accounts. In IWeb 08, I would set up several different user accounts on my M
-
Excise is not calculate in invoice verification
Dear All, I have one issue. We have create purchase order for project with account assignment category Q. We put excise (10.30) & Vat 15% in purchase order. In purchase order all value calculate properly. Good Receipt created against purchase order.
-
My home page is the default Google page but when i click on open new tab and it loads some other search engine's site instead. How do I change that back to Google? I've checked for any random add-ons but that doesnt seem to be the problem...
-
GR of subcontracting items without issuing components
Hi all I am facing a problem regarding subcontracting. In a PO of material X (item category L (subcontracting)) of required quantity 10, a component Y quantity 50 to make X is to be given to the vendor. The problem I am facing is that I am able to p
-
FR Chart Question: How to display % next to numbers?
Hi FRville residents, I am building a report that is mapped to the Actual/Budget column. In the Grid, I added % sign through FR formatting. When I map this column in my chart, and display the value, the chart shows values only. For example let say fo