Results 1 to 15 of 15
  1. #1
    Join Date
    Apr 2010
    Posts
    8
    Rep Power
    0

    Default I need help creating this program

    I am stuck in programming this last project for java 1 class.
    Here is the assignment:

    Part I: Print out the two arrays: (Be sure to do this first)
    Anne 30
    Bob 150
    Ralph 305
    Tim 225
    Barbara 135
    Jane 160
    Steve 80
    Tom 200
    Mike 165
    Shirley 90
    Pam 100
    Frank 120

    Part II: The elevators in our building have an 1100 lb. load limit. Determine which people in the list above get on the elevator. Print their names, weights, total weight, and how many got on.

    Part III: Rearrange these people in ascending sequence by weight and print the two arrays. Determine again how many may ride the elevator, printing out their names, weights, total weight and the number of how many people got on.

    Part IV: Rearrange these people in ascending sequence by name (USE A DIFFERENT SORT ALGORITHM THAN THE ONE YOU USED IN PART II) and print the two arrays. Determine again how many may ride the elevator, printing out their names, weights, total weight and the number of how many people got on.

    Part V: Have the program determine which method allowed the most people to get on the elevator.


    I have made multiple classes, but I am completely lost of what to do next.
    public class Person
    {
    private String name;
    private int weight;

    //default
    public Person()
    {
    name = "";
    weight = 0;
    }

    //overloaded
    public Person(String n, int w)
    {
    name = n;
    weight = w;
    }
    public String getName()
    {
    return name;
    }
    public int getWeight()
    {
    return weight;
    }
    public void setName(String n)
    {
    name = n;
    }

    public void setWeight(int w)
    {
    weight = w;
    }

    public String toString()
    {
    return name + "is " + weight + " pounds.";
    }
    }
    my second class
    public class People
    {
    private Person[] elev;
    private int count;

    public People(int size)
    {
    elev = new people[size];
    count = 0;
    }
    public void add(Person x)
    {
    elev[count] = x;
    count++;
    }
    if list.i.getName()compareTo
    public String toString()
    {
    String out ="";
    for (int i=0; i<count; i++)
    out+= (i + ":\t" + elev[i]);
    return out;
    }
    }

    and my main
    import java.util.Scanner;
    import java.io.*;

    public class Elevator
    {
    public static void main (String[] args) throw IOException
    {
    Scanner scan = new Scanner(new File("elevData.txt"));
    int s = scan.nextInt();
    Person loader = new Person();
    People holder = new People(s);


    do
    {
    loader.setName(scan.next());
    loader.setWeight(scan.nextInt());
    holder.add(loader);
    }
    while(scan.hasNext());

    System.out.println("The array is " + holder);




    if(loader<1100)


    }
    }
    Any help would be much appreciated.

  2. #2
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Please use CODE tags when posting code.

    I like your thinking, but the assignment says "two arrays" and not one array of Person objects. I'd probably still do it your way, if you think you can get away with it.

    "elev" is a bad name for your array variable in your People class. Just call it "people" or "persons". There is no reason for the People class to know anything about elevators. The class name itself is not great -- class names should generally be singular nouns. "Group" might be better.

    You need to write your sort methods (probably in your People class) and then you need a Person[] fillElevator(Person[] potentialRiders, int weightLimit) method in your Elevator class. Create your Person[] result array, then iterate through potentialRiders, adding each Person to result until you reach weightLimit. You also need a listRiders() method.

    That should get you going. Show us what you come up with, and remember to use CODE tags.

    -Gary-

  3. #3
    Join Date
    Apr 2010
    Posts
    8
    Rep Power
    0

    Default

    Thanks for your help. This is what I have come up with so far.
    Java Code:
    public class Group
    {
    	private Person[] persons;
    	private int count;
    	
    	public Group(int size)
    	{
    		persons = new people[size];
    		count = 0;
    	}
    	public void add(Person x)
    	{
    		persons[count] = x;
    		count++;			
    	}
    	public Person[] fillElevator(Person[] potentialRiders, int weightLimit)
    	{
    	
    		weightLimit = 1100;
    		totalWeight = 0;
    		potentialRiders = 0;
    		for(int i=0; i<persons.length; ++i)
    		{
    			
    			if(totalWeight <= weightLimit)
    				potentialRiders++;
    			else
    				break; 	
    		}
    	
    	}
    	public 
    	{
    		if persons[i].getName()compareTo
    	}
    
    	public sortWeights(int[] w;String[]n)
    	{
    		int weightIndex;
    		for (int i=0; i < persons.length-1; i++)
    	   {
    			weightIndex = i;
    			for (int j = i+1; j < persons.length; j++)
    				if (persons[j] < persons[weightIndex])
    					weightIndex = j;
    
    			int temp = persons[i];
    			persons[i] = persons[weightIndex];
    			persons[weightIndex] = temp;
    		}
    
    	}
    	public String toString()
    	{
    		String out ="";
    		for (int i=0; i<count; i++)
    	    out+= (i + ":\t" + persons[i]);
    		return out;
    	}
    How do I add the potentialRiders' weights to the weightLimit? How does the other stuff I have look?

  4. #4
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    fillElevator() goes in your Elevator class, not your Group class. Group knows about a collection of Persons, but doesn't (shouldn't) know anything about elevators. Also, weightLimit is going to be passed into the method, not assigned within it (unless it's an instance variable, which it probably should be -- an Elevator should know its weightLimit). You have one Person[] passed in to the method (potentialRiders) and you need to create another Person[] that you will return (result). And since we're using raw arrays, you'll probably need two passes -- one to get the count, and another to actually load the array. (It's clumsy, and that's why developers tend to prefer ArrayList.)

    sortWeight() needs a return type (maybe void?). I would probably call it sortByWeight(), make it void, and have it just sort the internal persons array in place. Actually, it seems that's what you're doing, but you've passed in two parameters that you never use.

    This is not going to work:
    Java Code:
    				if (persons[j] < persons[weightIndex])
    because Person is not Comparable (maybe you want getWeight() here?) Also,
    Java Code:
    			int temp = persons[i];
    I think you mean:
    Java Code:
    			Person temp = persons[i];
    You're on the right track, though. Good luck!

    -Gary-

  5. #5
    Join Date
    Apr 2010
    Posts
    8
    Rep Power
    0

    Default

    I've been working on this for awhile. Today's the last day for me to turn it in. I cannot get it to work correctly. I have output, but with muchas problemas.
    Here is my Person class:
    Java Code:
    public class Person
    {
    	private String name;
    	private int weight;
    	
    	//default 
    	public Person()
    	{
    		name = "";
    		weight = 0;
    	}
    	
    	//overloaded
    	public Person(String n, int w)
    	{
    		name = n;
    		weight = w;
    	}
    	public String getName()
    	{
    		return name;
    	}
    	public int getWeight()
    	{
    		return weight;
    	}
    	public void setName(String n)
    	{
    		name = n;
    	}
    	
    	public void setWeight(int w)
    	{
    		weight = w;
    	}
    	
    	public String toString()
    	{
    		return name +"\t"+ weight;
    	}
    }
    Here is my People class
    Java Code:
    public class People
    {
    	private Person[] persons;
    	private int count = 0;
    	
    	public People(int size)
    	{
    		persons = new Person[size];
    		count = 0;
    	}
    	public void add(Person x)
    	{
    		persons[count] = x;
    		count++;			
    	}
    	public int howMany()
    	{
    		int total = 0, i = 0;
    		do
    		{
    			total += persons[i].getWeight();
    			System.out.println("\n" + (i+1) + ":" + persons[i]);		
    			i++;
    			
    		
    		}while (total <= 1100);
    			System.out.println("The total weight is " + (total- (persons[i-1].getWeight())) );
    			return i-1;	 		
    	}
    	public int sortWeights()
    	{
    		int weightIndex;
    		for (int i=0; i < count; i++)
    	   {
    			weightIndex = i;
    			for (int j = i+1; j < persons.length; j++)
    				if (persons[j].getWeight() < persons[weightIndex].getWeight())
    					weightIndex = j;
    
    			Person temp = persons[i];
    			persons[i] = persons[weightIndex];
    			persons[weightIndex] = temp;
    			
    		}
    		return howMany();
    	}
    	public int sortNames()
    	{
    		int nameIndex;
    		for (int i=0; i < count; i++)
    	   {
    			nameIndex = i;
    			for (int j = i+1; j < persons.length; j++)
    			if(persons[i].getName().compareTo(persons[nameIndex].getName())>0)
    					nameIndex = j;
    		
    		Person temp = persons[i];
    		persons[i] = persons[nameIndex];
    		persons[nameIndex] = temp;
    		}
    		return howMany();
    	}
    	
    	public String toString()
    	{
    		String out ="";
    		for (int i=0; i<count; i++)
    	    out += ("\n"+(i+1) + ":\t" + persons[i]+"\n");
    		return out;
    	}
    }
    Here is my driver called Elevator:
    Java Code:
     import java.util.Scanner;
       import java.io.*;
    
        public class Elevator
       {
           public static void main (String[] args) throws IOException
          {
             Scanner scan = new Scanner(new File("elevData.txt"));
             int s = scan.nextInt();
          
             int count=0;
             int i = 0;
             int ctA = 0; int ctB = 0; int ctC = 0;
             	
             People holder = new People(s);
          
             System.out.println("The original array is ");
       		System.out.println(holder);	      
    			do
             {
    				Person loader = new Person();
                loader.setName(scan.next());
                loader.setWeight(scan.nextInt());
                holder.add(loader);
    				i++;
             }
             while(scan.hasNext());
         	
    			ctA = holder.howMany();
             System.out.println("For a regular day " + ctA +" people got on.");
          	
    			
             System.out.println("The array in ascending sequence by weight is ");
             ctB = holder.sortWeights();
             System.out.println("After sorting the people by weight "+ctB +" people got on");
          
             System.out.println("The array in ascending sequence by name is ");
             ctC = holder.sortNames();
             System.out.println("After sorting the people by name "+ctC+" people got on");
          
          
             if(ctA > ctB && ctA > ctC)
             {
                System.out.println("The first system worked the best");
             }
             else if(ctB > ctA && ctB > ctC)
             {
                System.out.println("The second system worked the best");
             }
             else 
             {
                System.out.println("The last system worked the best");
             }
          }
       }
    And here is my text file that I used.
    12
    Anne 30
    Bob 150
    Ralph 305
    Tim 225
    Barbara 135
    Jane 160
    Steve 80
    Tom 200
    Mike 165
    Shirley 90
    Pam 100
    Frank 120

    I would be extremely thankful for your help.

  6. #6
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,679
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by LostinJavaLand View Post
    Part V: Have the program determine which method allowed the most people to get on the elevator.
    I especially like this part of the assignment so I dusted off an old knapsack class of mine; a knapsack has a capacity (your elevator can lift 1100lbs), a person takes up capacity (their weight) and have a value (all equal for each person). How to fill up the knapsack given the capacity constraint so that the sum of the values is maximized (read: as many peoply can be stuffed in that elevator).

    A person is either stuffed in that elevator or not. When s/he is, the problem is reduced to a lesser capacity and a set of persons minus this current person. When a person doesn't fit in the elevator obviously we don't even try to stuff him in. That's how my program works. It reads the following data file:

    Java Code:
    1100 12
    1 30
    1 150
    1 305
    1 225
    1 135
    1 160
    1 80
    1 200
    1 165
    1 90
    1 100
    1 120
    The first line contains the capacity of the elevator and the number of persons. The following lines are the values of the persons and their weight. I saved this file in c:/tmp/data.txt

    Here is the class:

    Java Code:
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    
    public class Knapsack {
    
    	private Item[] items;
    	private int nofItems, capacity;
    
    	private void initialize() throws FileNotFoundException {
    
    		Scanner input= new Scanner(new File("c:/tmp/data.txt"));
    
    		capacity= input.nextInt();
    		nofItems= input.nextInt();
    		items= new Item[nofItems];
    		for (int i= 0; i < nofItems; i++)
    			items[i]= new Item(input.nextInt(), input.nextInt());
    
    		total= 0L;
    		cut= 0L;
    	}
    
    	private Solution solve(int allowed, int cap) {
    
    		Solution take, dontTake;
    
    		if (allowed < 0)
    			return new Solution(nofItems);
    
    		total++;
    
    		dontTake= solve(allowed-1, cap);
    
    		if (items[allowed].weight > cap) {
    			cut++;
    			return dontTake;
    		}
    
    		take= solve(allowed-1, cap-items[allowed].weight).take(items, allowed);
    
    		return (take.value > dontTake.value)?take:dontTake;
    	}
    
    	private long total;
    	private long cut;
    	
    	public static void main(String[] args) throws FileNotFoundException {
    
    		Knapsack k= new Knapsack();
    		k.initialize();
    
    		Solution b = k.solve(k.nofItems-1, k.capacity);
    
    		System.out.println("Total Value: " + b.value);
    		System.out.println("Total Steps: " + k.total);
    		System.out.println("Total Cuts : " + k.cut);
    		int w= 0;
    		for (int i= 0; i < k.nofItems; i++) {
    			if (b.taken[i]) {
    				System.out.println(i + ": " + k.items[i]);
    				w+= k.items[i].weight;
    			}
    		}
    		System.out.println("Total weight: "+w);
    	}
    }
    
    class Solution {
    
    	boolean[] taken;
    	int value;
    
    	Solution(int nofItems) {
    		this.taken= new boolean[nofItems];
    	}
    
    	Solution take(Item[] items, int rank) {
    
    		this.value+= items[rank].value;
    		this.taken[rank]= true;
    		return this;
    	}
    }
    
    class Item {
    
    	int value, weight;
    
    	public Item(int value, int weight) {
    		this.value= value;
    		this.weight= weight;
    	}
    
    	public String toString() {
    		return value + " " + weight;
    	}
    }
    The solution it came up with is:

    Java Code:
    Total Value: 9
    Total Steps: 3526
    Total Cuts : 342
    0: 1 30
    1: 1 150
    3: 1 225
    4: 1 135
    5: 1 160
    6: 1 80
    9: 1 90
    10: 1 100
    11: 1 120
    Total weight: 1090
    The elevator is nearly full ;-)

    kind regards,

    Jos
    Last edited by JosAH; 04-28-2010 at 06:38 PM.

  7. #7
    Join Date
    Apr 2010
    Posts
    8
    Rep Power
    0

    Default

    Thank you very much Jos. Nifty program.

  8. #8
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Yeah, JosAH's method does give the absolute solution to the problem at hand, but I think what your teacher had in mind was to just fill the persons into the elevator sequentially from your array, first unsorted, then sorted by weight, then sorted by name. Then you compare the results to see which array sequence gives the best (most persons) result. If you decide to use Jos' solution, be sure to study it and understand it, in case your teacher gets suspicious, since it's a bit more advanced than what the assignment was about (that is, if I understood the instructions correctly).
    Oh, and to Jos, really cool solution by recursion. I'm currently attending a class that focuses on recursion at my uni, this will come in pretty handy!
    Ever seen a dog chase its tail? Now that's an infinite loop.

  9. #9
    Meta is offline Member
    Join Date
    Mar 2010
    Posts
    78
    Rep Power
    0

    Default

    i have a question about this guys program. are those separate programs, that interact with each other. our are they in one program?

  10. #10
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    It is one program consisting of multiple classes in multiple source code files. This is not at all unusual for Java.

    -Gary-

    EDIT: To be clearer, I was talking about LostInJavaLand's code. JosAH's is one program consisting of multiple classes in one source code file. This is legal because only one of the classes in the file is public and has a main() method.
    Last edited by gcalvin; 04-28-2010 at 10:15 PM.

  11. #11
    Meta is offline Member
    Join Date
    Mar 2010
    Posts
    78
    Rep Power
    0

    Default

    can you explain how they work together , if they are separate files

  12. #12
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Quote Originally Posted by Meta View Post
    can you explain how they work together , if they are separate files
    Well, let's start with his Person class. It's public, has a public constructor, and several public methods. That means that any other code can create Person objects and call their methods, in very much the same way that your code can create ArrayList or JTextField or Random objects. His People class takes advantage of that and creates an array of Person objects. And his Elevator class in turn creates and uses a People object.

    You do have to make sure that all the necessary .class files are in directories that are on your CLASSPATH, but other than that and the access restrictions (public, private, protected, etc.) there's not much to it.

    -Gary-

  13. #13
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,679
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by m00nchile View Post
    Oh, and to Jos, really cool solution by recursion. I'm currently attending a class that focuses on recursion at my uni, this will come in pretty handy!
    Thanks; the core of the algorithm is really simple: assume all those people are standing in line; the range of people [0, allowed] can potentially be put in the elevator. For every person the algorithm either tries to put that person in the elevator (if it can still fit the person in) or it doesn't. Note that first the 'don't take' option is executed all the way down to where no more persons are left to chose; only then a new solution is created and people are stuffed in when the algorithm (recursively) reaches the 'take' option. Basically all combinations are checked and the best solution is kept. At the end some statistics are printed: the higher the 'cut' number (depending on the order of the people) the better the algorithm performed. Try different orders for those people and see for yourself.

    kind regards,

    Jos

  14. #14
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    Quote Originally Posted by JosAH View Post
    .. the higher the 'cut' number (depending on the order of the people) the better the algorithm performed ...
    That's an especially cool property.

    r035198x(<----choking from all the dust from Jos' sack.

  15. #15
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,679
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by r035198x View Post
    That's an especially cool property.
    It's cute isn't it? And the bounding condition is just trivial: if a person is too heavy to fit in the elevator (given a certain filling already) there's no need to explore all combinations with that person on board because they're all infeasible. Even for this small problem (12 persons) it had to travers 4096 possibilities but by applying 342 cuts it only had to investigate 3526 possibilities). Cutting on branches always pays back. Personally I'm too stupid to come up with a more 'intelligent' cut strategy.

    r035198x(<----choking from all the dust from Jos' sack.
    There are a whole lot more tricks in there so you'd better watch out! ;-)

    kind regards,

    Jos

Similar Threads

  1. Need help creating this java program
    By SolidifieD in forum New To Java
    Replies: 1
    Last Post: 02-23-2010, 01:46 AM
  2. Replies: 3
    Last Post: 08-10-2009, 07:34 AM
  3. Replies: 2
    Last Post: 02-23-2009, 03:18 AM
  4. Creating Program Stubs
    By Bascotie in forum New To Java
    Replies: 2
    Last Post: 01-18-2009, 07:27 AM
  5. Creating installer for java program
    By priyanka.dandekar in forum Advanced Java
    Replies: 9
    Last Post: 10-05-2008, 11:04 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •