Help sort topic revised
Sorry about that. Before i proceed with the code I will say that I need help trying to determine where to put a sort statement and what sort statement should I use. I have three classes and have no idea how to sort the items by Product name. For instance, I have staples, books, and printers in my code. How do I get it to display these names and all of the corresponding information in alphabetical order. So with that said, here is the code.
Program part 1:
// CheckPoint: Inventory Program Part 1
// Display product information
public class Product1 //declare class
//declare instance variables
private int productNumber,
inStock;private String productName; // List of instance variables unique to object
private double unitPrice;
//constructor to handle no input and set defaults
public Product1()
//constructor to handle input parameters
public Product1( int number, String name, int stock, double perPrice )
productNumber = number;
productName = name;
inStock = stock;
unitPrice = perPrice;
public void setProductNumber( int number ) //stores product number
productNumber = number;
public void setProductName( String name ) //stores product name
productName = name;
public void setInStock( int stock ) //stores amount of product in stock
inStock = stock;
public void setUnitPrice( double perPrice ) //stores the unit price of product
unitPrice = perPrice;
public int getProductNumber() //allows a call to retrieve product number
return productNumber;
public String getProductName() //allows a call to retrieve the product name
return productName;
public int getInStock() //allows a call to retrieve stock info
return inStock;
public double getUnitPrice() //allows a call to retrieve unit price
return unitPrice;
public double getInventoryValue()
return ( (double)inStock * unitPrice );
Program part 2:
import java.text.DecimalFormat;// Imports a utility that will format items to currency.
public class Inventory1
private final int maxInventory = 30; // Sets maximum number of elements in the array.
private Product1 items[] = new Product1[ maxInventory ]; // creates an array of Product1 objects comprised of all of the components.
DecimalFormat formatter = new DecimalFormat( "$##,###.00" ); creates a formatter object to set items to currency display.
public void addProduct( Product1 item ) // method adds a product to an array and sets it to the variable name item.
for ( int i = 0; i < maxInventory; i++ )
if (items[i] == null)
items[i] = item;
return;
public double getTotalInventoryValue() // method ensures if there are items in array and adds inventory values of specific products to each other.
double sum = 0.0;
for ( Product1 item : items )
if ( item != null )
sum += item.getInventoryValue();
return sum;
public void displayInventory() // Ensures that if there are items in the array and displays them in chart form.
boolean hasItems = false;
for ( Product1 item : items )
if ( item != null)
hasItems = true;
System.out.printf( "%8d%12s%11d%13.2f%14.2f", item.getProductNumber() , item.getProductName(), item.getInStock(), item.getUnitPrice(),
item.getInventoryValue() );
System.out.println( "" ); // display space
System.out.println("");
Program part 3:
import java.text.DecimalFormat; // import to display selected items as currency.
public class InventoryTest1
static DecimalFormat formatter = new DecimalFormat( "$##,###.00" ); // object created for use to any object that is created as an instance of this
public static void main( String args[] ) // executes program.
Product1 item1 = new Product1( 001, "Staples", 5, 2.99 ); // Initialize objects with parameters.
Product1 item2 = new Product1( 002, "Books", 10, 15.00 );
Product1 item3 = new Product1( 003, "Printers", 20, 55.00 );
Inventory1 myInventory1 = new Inventory1(); // Initialize object of Inventory1.
System.out.println("");
System.out.printf( "%s%12s%11s%13s%14s", "Product#", "Name", "In Stock", "Unit Price", "Stock Value" );
System.out.println("");
System.out.println("");
myInventory1.addProduct( item1 );
myInventory1.addProduct( item2 );
myInventory1.addProduct( item3 );
myInventory1.displayInventory(); //call Inventory1 method to display product info.
System.out.println( "" ); // display space
System.out.println("");
System.out.println( "Total value of inventory is: " );
System.out.println ( formatter.format(myInventory1.getTotalInventoryValue() ) ); // display inventory total as currency.
Next time if you want to edit a post, use the edit button which appears at the right top corner of the posting. Do not use the browser back button for that. Otherwise you would create a new topic again, of which the forum regulars may see as very rude.
Another hint: the post message field has a 'Preview' tab. Make use of it if you just want a preview of how the post is going to look like.
Similar Messages
-
Help screen topics in itunes 11.2.2 are blank
When I go to the help menu, topics show up but upon clicking on a topic, screen shows up blank.
Try re-installing it.
iTunes 11.2.2 -
In oracle 6i there is an item property called, "Help Book Topic". Can some one tell me how to use this.
Regards
ZIAThis property was used by "Oracle Book" a product that doesn't exist anymore.
-
Need help Sorting an Arraylist of type Object by Name
Hey guys this is my first time posting on this forum so hopefully i do it the right way. My problem is that i am having difficulties sorting an Array list of my type object that i created. My class has fields for Name, ID, Hrs and Hrs worked. I need to sort this Array list in descending order according to name. Name is the last name only. I have used a bubble sort like this:
public static void BubbleSort(TStudent[] x){
TStudent temp = new TStudent();
boolean doMore = true;
while (doMore) {
doMore = false;
for (int i=0; i < x.length-1; i++) {
if (x.stuGetGPA() < x[i+1].stuGetGPA()) {
// exchange elements
temp = x[i]; x[i] = x[i+1];
x[i+1] = temp;
doMore = true;
before many time to sort an array of my class TStudent according to GPA. This time though i tried using an Array list instead of just a simple array and i can't figure out how i would modify that to perform the same task. Then i googled it and read about the Collections.sort function. The only problem there is that i know i have to make my own comparator but i can't figure out how to do that either. All of the examples of writing a comparator i could find were just using either String's or just simple Arrays of strings. I couldn't find a good example of using an Array list of an Object.
Anyways sorry for the long explanation and any help anyone could give me would be greatly appreciated. Thanks guys
Edited by: Brian13 on Oct 19, 2007 10:38 PMok still having problems I have this line of code to try and all Arrays.sort
Arrays.sort(Employee, TEmployee.FirstNameComparator);Then in my class TEmployee i have
public static Comparator FirstNameComparator = new Comparator() {
public int compare(Object employee, Object anotherEmployee) {
String lastName1 = ((TEmployee) employee).getEmpName().toUpperCase();
String lastName2 = ((TEmployee) anotherEmployee).getEmpName().toUpperCase();
return lastName1.compareTo(lastName2);
};Here is the rundown of what i have for this. I have 2 classes. One is called TEmployee and that class holds fields for Name, ID, Hrs Worked, Hourly Rate. Then i have another class called myCompany that holds an ArrayList of type TEmployee. Then i have my main program in a Jframe.
So maybe i am putting them in the wrong spots. The code in TEmployee thats make the comparator is fine. However when i try to call Arrays.sort from class myCompany i get this
cannot find symbol
symbol: method sort (java.util.Array list<TEmployee>.java.util.Comparator
location: class java.util.Arrays
I have to put the comparator in TEmployee right because thats where my fields for Name are? Do i call the arrays.sort from my main program or do i call that from the class myCompany where my ArrayList of TEmployees are stored?
Again guys thanks for any help you could give me and if you need any code to see what else is going on just let me know. -
Need help sorting an ArrayList of strings by an in common substring
I'm trying to sort a .csv file, which I read into an ArrayList as strings. I would like to sort by the IP address within the string. Can someone please help me figure out the best way to sort these strings by a common substring each has, which is an IP address.
I'm pretty sure that I need to use Collections some how, but I don't know where to begin with them besides trying to look online for help. I had no luck finding any good examples, so I came here as a last resort.
Thanks for any help provided.You need to write your own Comparator class. In the compare() method you substring out the two IP addresses, compare them and return appropriate value. Then you call Collections.sort() and pass your list and comparator.
-
Please help, sorting...
I have to sort a doubly linked list containing strings
I have to hard code a merge sort for this, but I have nooooo idea how to do this...
I know what a merge sort is, and how to do it with an int array, but string? and even worse, not an array but a doubly linked list...
please, I've been trying to understand this for hours now....
- DanIt is just like the collections "LinkedList", and I have a node class
class Node
Node next;
Node previous;
String element;
Node()
Node(String data)
element = data;
Node(String data, Node nextNode, NodePrevNode)
element = data;
next = nextNode;
previous = prevNode
}//class Node
my big problem is to sort the nodes in alphabetical order, I have tried to convert a mergesort for int[] but it doesn't work...
And I kind of have to use this kind of sort because it have to work well for very large n...
any help is very welcome - Dan -
WinHelp to HTML Help - missed topics
I'm creating HTML Help projects using RoboHTML version X5.0.2
by importing a WinHelp project created in RoboHelp for Word version
X5.0.1 - Microsoft Word 2000, Windows XP operating system (either
via the HLP or HPJ file).
After the process is complete, certain topics are not coming
over. I thought perhaps it was due to long tables, but some topics
with long tables came over. So, I'm not sure why these particular
topics are being missed. I checked to see if there's anything
unique about these topics (such as unnecessary non-scrolling
regions, etc.) but nothing is different.
Has anyone else experienced this problem?ellenu,
I am having the exact same issue, I'm also in the process of
creating HTML Help projects by importing a WinHelp project. When I
import my .HPJ (Winhelp project file) into RoboHelp for Word all of
the topics get loaded, and I am able to successfully re-compile
using any of the WinHelp layouts, all of the topics are included.
However, if I choose the Microsoft HTML Help layout only the first
19 topics get converted to HTML.
Also, If I try to import the .HPJ (Winhelp project file) into
RoboHelp HTML, the same problem occurs. The first 19 topics are
loaded and the rest go missing! I have even tried deleting what
would be topic 20, to see if it was an issue with that topic. No
go....
I would be most appreciative if anyone has any insight into
this issue.
Details:
Windows XP
WinHelp compiled using HCW.EXE version 4.03.0002
RoboHTML version X5.0.2 Build 801
RoboHelp for Word version X5.0.1 Build 606
Microsoft Word 2002
Deana -
Need help sorting 2 arrays linked by their indexes
I have 2 arrays that have been linked by the index of both arrays. The first array has to be sorted alphabetically, so I need a way to sort the 2nd array so that the indices match up again with the first array.
Now, I cannot change my ArrayList (i.e. TreeSet, List, etc.) since there is lots of code that would have to be changed. Here is my test code. Hopefully everyone is a fan of the television show Friends so that you can see how if I sort the firstName Array alphabetically, then I have to have the 2nd array sorted to be "linked" back to the first array based on the index. I am looking for ideas, but if you have simple code, that would be great too.
import java.util.*;
public class Test
public static void main(String[] args)
System.out.println("BEGIN TEST...");
Test test = new Test();
test.beginTest();
System.out.println("\nTEST COMPLETE!");
public Test(){}
public void beginTest()
ArrayList firstName = new ArrayList();
ArrayList lastName = new ArrayList();
//Add to firstName ArrayList
firstName.add("Ross");
firstName.add("Chandler");
firstName.add("Rachel");
firstName.add("Phoebe");
firstName.add("Joey");
//Add to lastName ArrayList
lastName.add("Geller");
lastName.add("Bing");
lastName.add("Green");
lastName.add("Buffay");
lastName.add("Tribbiani");
try
System.out.println("TESTING...\n");
for(int index=0; index<firstName.size(); index++)
String first = firstName.get(index).toString();
String last = lastName.get(index).toString();
System.out.println("Hi, I am " + first + " " + last + ".");
catch(Exception X) { System.out.println("EXCEPTION! "+X); X.printStackTrace(); }
}Keeping the list in synch is conceptually easy.
Basically anything you do to the one List, you have to do to the other in order to keep them consistent.
How are you sorting your "firstnames" list?
Using the Collections.sort method, or some manual coding?
Would it be possible to change your datastructure from "parallel arrays" to "List of people objects"
iepublic class Person {
String firstName;
String lastName;
public Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
// appropriate getter/setter methods
}Then you could build up your list like this:
List friends = new ArrayList();
friends.add(new Person("Ross", "Geller"));
friends.add(new Person("Chandler", "Bing"));
...Now when you sort the list, the last name always goes with the first name because they are in the same object.
You then write different Comparator objects to impose different orderings.
Hope this helps,
evnafets -
HTML Help: Showing Topic IDs in Search
We have moved from WinHelp to Microsoft HTML Help. One of our
customers discovered that topic ids are appearing in the "Select
topic to Display" box of the Search tab. In WinHelp, only topics
with Topic Names would appear here. These topics that are appearing
are topics that were created to display on hotspots on graphics in
the help, so I do not want them to display in the search. Is there
a way to keep the search from displaying topics without names?
Thanks!
ChrisHi there
No, X5 is a few versions old and doesn't have the
capabilities 8 does.
So here is how you might accomplish it using X5. I seldom
will ever recommend to someone to do this but in this case it's
necessary. Step behind RoboHelp's back and use Windows Explorer.
Locate the offending topics and rename them from the .htm file
extension to .xhtm. This action will cause RoboHelp to sense them
as missing in action and list them with a red X. In RoboHelp you
will add the files to Baggage Files in the appropriate folder. You
will also delete the "missing" topics. Finally you will amend any
links so that they now point to their .xhtm counterparts.
This would keep them from being searched and allow them to
exist in the project.
Cheers... Rick -
i have a brand new MuVo n200
i need help, i put my cd's in and everyhting and i filled it with songs ans i can play them and everything, but i hate thats itssorted in ABC order. i cannot figure how to put them so it is in order by the CD or the bandname.
please help.
message me on aim if you want [email][email protected]][email protected][/url]To group the songs into albums or artist groups, I would definitely suggest putting all the tracks from each album/group in its own folder on your PC and put the folder on the muvo in just the same way as you would put a single mp3. The player (in normal play mode) will then play each folder all the way through before moving on to the next one alphabetically (or numerically, if you put numbers at the start of the folder names) and you can then use 'skip folder' to skip through to find the particular album or artist you're looking for. Play around with the shuffle modes too - you can shuffle within folders or just shuffle everything if you want.
Tracks will normally be played alphabetically. To get them to play in order of track number, put numbers at the beginning of each file name. E.g.: file 'examplesong.mp3' would become '0_ examplesong.mp3' If you've got tonnes of songs and you're worried about it taking ages, the computer will do it for you! Click on 'my computer', then click on 'Muvo N200 media explorer'.. This shows the contents of your player. Choose a folder to reorder the songs in and click on it to display the songs. In the pictures along the top of the window, 4th from the right is an icon with a downward facing arrow and an A above a Z. Click on this, it's called 'custom sort'. You can then use the arrows at the bottom to change the order of your tracks to how you want them. Click OK, and they'll all be numbered in that order!
For instructions on how to create folders in mediasource, read the thread in this link:
http://forums.creative.com/creativelabs/board/message?board.id=dap&message.id=926
I don't think you can put folders within folders in the muvo, but just the one layer really helps organisation.
Hope that helps!
x Flaneur
PS- scroll down in the thread in the link: Jeremy CL was nice enough to give pictures in his instructions! If you'd like more help, type 'create folders' or something into the forum search as there's probably quite a lot of advice kicking about here!Message Edited by flaneur on 03-27-2005 :8 PM -
Has anybody fond a way to sort contacts by company?
I only see by name first or last only.
Am I missing something or is apple... PLEASE HELP!
I dont wont to delete 1000 names just to get the company name to show up in contacts...One more thing about groups: each contact can live in more than one group. In addition to all the regular groups I use, I also created a "companies" group just to handle this issue. First I made a smart group, set the condition to be "company is assigned", which populated it with all contacts that have a company listed in their contact info. Then I made a regular "companies" group, dragged all the contacts in the smart group into the new group, and synced. So now if I'm looking for a company, I just choose the companies group and look through those.
-
Windows 7 help The topic you are looking for is not available in this version of Windows
When I click on help, I get this message: The topic you are looking for is not available in this version of Windows.
I forget what my topic was, however, that is the response for any I try to get help for.Hi Akikuno
It sounds like you are having issues with your help not coming up when you need to use it. I am providing you a link to a Microsoft Forum Thread where they are addressing the exact error message you are receiving.
http://answers.microsoft.com/en-us/ie/forum/ie9-windows_7/the-topic-you-are-looking-for-is-not-avail...
I would like to thank you for posting on the HP Forums and hope this resolves your issue so you can go back to enjoying your HP product. Have a great day!
Please click the "Thumbs Up" on the bottom right of this post to say thank you if you appreciate the support I provide!
Also be sure to mark my post as “Accept as Solution" if you feel my post solved your issue, it will help others who face the same challenge find the same solution.
Dunidar
I work on behalf of HP
Find out a bit more about me by checking out my profile!
"Customers don’t expect you to be perfect. They do expect you to fix things when they go wrong." ~ Donald Porter -
Urgent help: sort hashtable
can anyone please show me som code that sort a Hashtable, like the one below, by its keys.
Hashtable ole = new Hashtable();
ole.put(new Integer(2),"erik2");
ole.put(new Integer(1),"erik1");
ole.put(new Integer(4),"erik4");
ole.put(new Integer(3),"erik3");
( yes I need to access the items in a particular order )http://forum.java.sun.com/thread.jsp?forum=31&thread=151707
Don't post identical questions. You will make ppl angry and no one will want to help you. -
I need help sorting an Array.
Hi, I need to make a program that reads a string (sentence), then it counts the number of times each letter is "typed". As an optional challenge, the teacher told us to sort the results from the most repeated, to the least.
My program is working pretty well, here is the code:
import java.lang.String;
//import java.util.Collections;
//import java.util.*;
public class count {
final int alpha = 66;
int [] lower = new int [alpha];
* @param args
public static void main(String[] args) {
// TODO Auto-generated method stub
java.util.Scanner in = new java.util.Scanner (System.in);
char current;
final int alpha = 66;
int [] lower = new int [alpha];
int Spaces = 0;
System.out.println("Enter a sentence:");
String line = in.nextLine ();
//int length = line.length();
line = line.toLowerCase();
for (int ch = 0; ch < line.length(); ch++)
current = line.charAt(ch);
if (current >= 'a' && current <= 'z')
lower[current-'a']++;
else if (current == ' ')
Spaces ++;
System.out.println();
for (int letter=0; letter < lower.length;letter++)
if (lower[letter]>0){
System.out.print((char)(letter + 'a'));
System.out.println(": " + lower[letter]);
System.out.println ();
System.out.println ("Spaces: " + Spaces);
}[now, I want to sort the results. I tried using Arrays.sort(lower); but it doesnt work as it should. Example:
String: Hello
not sorted:
e: 1
h: 1
l: 2
o: 1
Spaces: 0
"sorted":
: 1
.:1
]:1
~:2
Spaces: 0
I would really appreciate your help.
Thanks, J. FlemmingSince you didn't post your Arraays.sort code, I can't
tell what you did wrong.
What does your array store? Element 0 is the number
of 'a' occurences, 1 is 'b', etc?
If so, then when you sort that, you'll have no idea
which element corresponds to 'a'. You'll need a
different approach for that. For instance, a class
that encapsulates two pieces of data: character and
number of occurences. You could then implement your
own sort, or learn how to use Comparable/Comparator.
Making Java
Objects Comparable
http://java.sun.com/docs/books/tutorial/collections/in
terfaces/order.html
http://www.javaworld.com/javaworld/jw-12-2002/jw-1227-
sort.htmlAs I said in my original post, I used Arrays.sort(lower), which is probably wrong. My Arrays does work as you described, element 0 is the numer of occurrences of 'a', and 1 is the number of occurrences of 'b' and so on. Thanks for your responce. Im looking into what you said. Thanks again.
Message was edited by:
Flemm.John -
Help sorting an array of objects needed please.
I am trying to sort the array Students[] in descending order of Fees due. Using the code below I get a null pointer error at runtime. The array is not completely full, it has 20 cells, but the variable studentArrayCounter holds the number of used cells. The 'getFeesDue()' code returns an integer value.
Any help is appreciated.
// Sort Student Records Method
public void sortStudentRecords()
int loopCount = 0;
for (loopCount = 1; loopCount < studentArrayCounter; loopCount ++)
if(Students[loopCount].getFeesDue()>Students[loopCount-1].getFeesDue())
SortStudents[0]=Students[loopCount-1];
Students[loopCount-1]=Students[loopCount];
Students[loopCount]=SortStudents[0];
}Also, unless the excersize is to write a sort algorigthm (which I kinda doubt) you should use Arrays.sort
Arrays.sort(Students, new Comparator() {
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
return s1.getFeesDue() - s2.getFeesDue();
});
Maybe you are looking for
-
Pages returning error message "The document (name) couldn't be opened"
Okay so here is my problem: I made a document in Pages the other day (a list of books I own) and after spending an hour or so on it I saved, closed Pages and went and did something else. The next day I came to open it again to add something and Pages
-
I Have downloaded the 64 bit version of iTunes for my Sony running Windows 8. Install went fine and I can get in to iTunes and see the music residing on this machine. However, everytime that I try to run iTunes Match Windows crashes. So frustratin
-
I can't open a file i was working on yesterday in Photoshop!
It says 'Could not complete your request because the file is not compatible with this version of Photoshop'. I'm on Photoshop CS3. HELP!!!!!
-
Support for multiple languages in Skype Chat
Hi, on my Windows 8.1 laptop, the default language is English, but I have several Windows language packs installed. In Outlook or within a web browser, I can switch easily between languages when typing, and create emails in different languages simult
-
When l want to upgrade in Appstore a message tells me that this update is available for another account...but not for mine ! l think that this upgrade is part of a upgrade for OS Lion because l did not bought iPhoto in the appstore.