Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 23 of 23

Thread: Using Random class

  1. #1
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Question Using Random class

    I have a couple of classes, not related to my big project, which still is being ignored by everyone for some odd reason, that randomly pick a number of students as a class size and also randomly pick students, but use a different Random so I don't keep picking the same Random student like 20 times, or even more than once for any class.

    /**
     * 
     */
    package DiscreteMathProject;
     
    /**
     * @author pradcoc
     *
     */
    public class Student {
     
    	private String name;
     
    	public Student(String name)
    	{
    		name = this.name;
    	}
     
    	public String getName()
    	{
    		return name;
    	}
     
     
    }

    package DiscreteMathProject;
     
    import java.util.ArrayList;
    import java.util.Random;
     
    /**
     * @author pradcoc
     *
     */
    public class Class {
     
    	private Student[] students;
    	private String[] times;
    	private String name;
    	private String time;
    	private int size = 0;
    	private Random r,r2;
    	private Random[] random;
    	private ArrayList<Student> aList;
    	private ArrayList<String> aList2;
     
    	public Class(String name)
    	{
     
    		name = this.name;
    		times = new String[10];
    		times[0] = "8:00 a.m.";
    		times[1] = "9:30 a.m.";
    		times[2] = "11:00 a.m.";
    		times[3] = "12:30 p.m.";
    		times[4] = "2:00 p.m.";
    		times[5] = "3:30 p.m.";
    		times[6] = "5:00 p.m.";
    		times[7] = "6:30 p.m.";
    		times[8] = "8:00 p.m.";
    		times[9] = "9:30 p.m.";
    		aList = new ArrayList<Student>();
     
     
    	}
    	public String getTime()
    	{
    		r = new Random();
    		int x = r.nextInt(10);
    		time= times[x];
    		return time;
    	}
     
    	public String getName()
    	{
    		return name;
    	}
     
    	public void addStudents(Student s)
    	{
     
    		aList.add(s);
     
    	}
     
    	public ArrayList<Student> getArrayList()
    	{
    		return aList;
    	}
     
    	public int getSize()
    	{
    	r2 = new Random();
    	int x = r.nextInt(51);
    	size = x;
    	return size;
    	}
     
    	public String toString()
    	{
    		String str = "The class: " + getName() + " is at " + getTime() + "and has " + getSize() + " students." + 
    		" The students in it are: " + getStudentsInClass() + "." ;
    		return str;
    	}
     
    	public String getStudentsInClass()
    	{
    		aList2 = new ArrayList<String>();
    		for (int i = 0; i < getSize(); i++)
    		{
    			aList2.add(aList.get(i).getName());
    		}
     
    		String str = aList2.toString();
    		return str;
    	}
    }

    package DiscreteMathProject;
     
    import java.util.ArrayList;
    import java.util.Random;
     
    public class MainClass {
     
    	private String[] studentNames;
    	private Student[] students;
    	private Class[] classes;
    	private String[] classNames;
    	private ArrayList<Student> aList2;
    	private Random[] random;
     
    	public MainClass()
    	{
    		classes = new Class[20];
    		studentNames = new String[400];
    		students = new Student[400];
    		studentNames[0] = "Joe McDonald";
    		studentNames[1] = "Paul Adcock";
    		studentNames[2] = "Darth Vader";
    		studentNames[3] = "Peter Parker";
    		studentNames[4] = "Abraham Lincoln";
    		studentNames[5] = "Albert Einstein";
    		studentNames[6] = "Spongebob Squarepants";
    		studentNames[7] = "James Bond";
    		studentNames[8] = "Sherlock Holmes";
    		studentNames[9] = "John Wayne";
    		studentNames[10] = "Walter Payton";
    		studentNames[11] = "George Herman (Babe) Ruth";
    		studentNames[12] = "Susan B. Anthony";
    		studentNames[13] = "Martin Luther";
    		studentNames[14] = "Julius Ceasar";
    		studentNames[15] = "Adolf Hitler";
    		studentNames[16] = "Joseph Stalin";
    		studentNames[17] = "Fidel Castro";
    		studentNames[18] = "Ivan The Terrible";
    		studentNames[19] = "Jabba The Hutt";
    		studentNames[20] = "Luke Skywalker";
    		studentNames[21] = "Emperor Palpatine";
    		studentNames[22] = "Thomas Edison";
    		studentNames[23] = "Benjamin Franklin";
    		studentNames[24] = "Judas Iscariot";
    		studentNames[25] = "King David";
    		studentNames[26] = "Blaise Pascal";
    		studentNames[27] = "John Watson";
    		studentNames[28] = "James Watt";
    		studentNames[29] = "Henry Ford";
    		studentNames[30] = "Michael Jackson";
    		studentNames[31] = "Mohatma Ghandi";
    		studentNames[32] = "Emperor Mao";
    		studentNames[33] = "Robin of Locksley (Robin Hood)";
    		studentNames[34] = "King Richard The Lionhearted";
    		studentNames[35] = "Harry Potter";
    		studentNames[36] = "John Smith";
    		studentNames[37] = "King John";
    		studentNames[38] = "William The Conqueror";
    		studentNames[39] = "Bloody Mary";
    		studentNames[40] = "Johnny Cash";
    		studentNames[41] = "Sargon of Akkad";
    		studentNames[42] = "Prince Absalom";
    		studentNames[43] = "Eustace Clarence";
    		studentNames[44] = "Ronald Weasley";
    		studentNames[45] = "Rosa Parks";
    		studentNames[46] = "Sandra Day O'Connor";
    		studentNames[47] = "Queen Lucy Pevensie";
    		studentNames[48] = "John The Apostle";
    		studentNames[49] = "Kevin McAlister";
    		studentNames[50] = "Alex Pruitt";
    		studentNames[51] = "Guy Fawkes";
    		studentNames[52] = "Queen Heshepshut";
    		studentNames[53] = "King Ramases";
    		studentNames[54] = "King Xerxes of Persia";
    		studentNames[55] = "Nathan Hale";
    		studentNames[56] = "Patrick Henry";
    		studentNames[57] = "Jacob Marley";
    		studentNames[58] = "Ebenezer Scrooge";
    		studentNames[59] = "Saint Augustine";
    		studentNames[60] = "John Lennon";
    		studentNames[61] = "Forrest Gump";
    		studentNames[62] = "Jenny Gump";
    		studentNames[63] = "Luitenant Dan";
    		studentNames[64] = "John Q. Public";
    		studentNames[65] = "Bill Gates";
    		studentNames[66] = "Harriet Tubman";
    		studentNames[67] = "Sojourner Truth";
    		studentNames[68] = "Malcom Little(Malcom X)";
    		studentNames[69] = "Leonardo D. Caprio";
    		studentNames[70] = "Jack Philps";
    		studentNames[71] = "Paul Revere";
    		studentNames[72] = "Becky Thatcher";
    		studentNames[73] = "Tom Sawyer";
    		studentNames[74] = "Samual Clemmons(Mark Twain)";
    		studentNames[75] = "George Washington Carver";
    		studentNames[76] = "Paul Bunyan";
    		studentNames[77] = "Huck Finn";
    		studentNames[78] = "Picos Bill";
    		studentNames[79] = "Mark Anthony";
    		studentNames[80] = "Queen Cleopatra";
    		studentNames[81] = "Anne Frank";
    		studentNames[82] = "Eli Wesel";
    		studentNames[83] = "Eddie Brock";
    		studentNames[84] = "Thorin Oakenshield";
    		studentNames[85] = "Bilbo Bagins";
    		studentNames[86] = "Frodo Baggins";
    		studentNames[87] = "Sam Gamagee";
    		studentNames[88] = "Gandalf the Gray";
    		studentNames[89] = "Sauraman the Wise";
    		studentNames[90] = "King George III";
    		studentNames[91] = "William Wilberforce";
    		studentNames[92] = "Merry Brandybuck";
    		studentNames[93] = "Martin Luther King Jr.";
    		studentNames[94] = "Jackie Robinson";
    		studentNames[95] = "Sherwim Williams";
    		studentNames[96] = "John Menard";
    		studentNames[97] = "Chrisopher Columbus";
    		studentNames[98] = "Genghis Khan";
    		studentNames[99] = "Atilla The Hun";
    		studentNames[100] = "Al Capone";
    		studentNames[101] = "Napolean Bonepart";
    		studentNames[102] = "Marie Antionette";
    		studentNames[103] = "King Louis XVII";
    		studentNames[104] = "Napolean Blownapart";
    		studentNames[105] = "Yesser Arafat";
    		studentNames[106] = "Al Gore";
    		studentNames[107] = "Benedict Arnold";
    		studentNames[108] = "Tim Allen";
    		studentNames[109] = "George W. Bush";
    		for (int x = 110; x < 400; x++)
    		{
    			studentNames[x] = "Student " + x;
    		}
     
    		for (int y = 0; y < 400; y++)
    		{
    			students[y] = new Student(studentNames[y]);
    		}
     
    		classNames = new String[20];
     
    		classNames[0] = "Sleeping 101";
    		classNames[1] = "Partying 202";
    		classNames[2] = "Discrete Math";
    		classNames[3] = "Rocket Science";
    		classNames[4] = "Introduction to Data Structures";
    		classNames[5] = "Skipping 303";
    		classNames[6] = "Creative Writing";
    		classNames[7] = "Introduction to Technical Communication";
    		classNames[8] = "Easy Class";
    		classNames[9] = "Surviving College";
    		classNames[10] = "How To Outsmart the Profs";
    		classNames[11] = "Astronomy";
    		classNames[12] = "Thermodynamics";
    		classNames[13] = "Long-winded Lectures 404";
    		classNames[14] = "System Design";
    		classNames[15] = "Physics";
    		classNames[16] = "Chemistry";
    		classNames[17] = "Tutoring";
    		classNames[18] = "Politics 204";
    		classNames[19] = "Very Hard Class";
     
    		for (int z = 0; z < 20; z++)
    		{
    			classes[z] = new Class(classNames[z]);
    		}
     
     
    	}
     
    	public static void main(String[] args)
    	{
    		MainClass mainC = new MainClass();
    	}
    }

    I need to figure out how to add the class size, which is a Random number, a Random number of different students. It doesn't matter as long as no student is in more than 5 classes and no student is in any class twice.
    Last edited by javapenguin; October 25th, 2010 at 03:53 PM. Reason: Fixing a Null Poiinter Exception


  2. #2
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

    Ahhh...I see that class size is random, and it will throw Index Out of Bounds somehow.

    Perhaps it'll fix that when I can figure out how to add the random size and add random, not same students, number of students to each class.

  3. #3
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

    Ok, why does it need to be getSize() + 1?

    for (int k = 0; k < classes[0].getSize() + 1; k++)
    {
    classes[0].add(students[k]);
    }
    and even then everything is null. Why?

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Using Random class

    If you don't want to keep picking the same random number, store them in a Set. Then check for each random number whether the set contains that number.
    Random rand = new Random();
    Set<Integer> mix = new HashSet<Integer>();
    for ( int i = 0; i < 10; i++ ){
        int rN = rand.nextInt();
        while ( set.contains(rN) ){//already chose
            rN = rand.nextInt();//get another
        }
        set.add(rN);
    }
    Doing so this way however, you have to be careful that the loop count isn't greater than the value of the max random value, or you will enter into an infinite loop.

  5. The Following User Says Thank You to copeg For This Useful Post:

    javapenguin (October 25th, 2010)

  6. #5
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

    Quote Originally Posted by copeg View Post
    If you don't want to keep picking the same random number, store them in a Set. Then check for each random number whether the set contains that number.
    Random rand = new Random();
    Set<Integer> mix = new HashSet<Integer>();
    for ( int i = 0; i < 10; i++ ){
        int rN = rand.nextInt();
        while ( set.contains(rN) ){//already chose
            rN = rand.nextInt();//get another
        }
        set.add(rN);
    }
    Doing so this way however, you have to be careful that the loop count isn't greater than the value of the max random value, or you will enter into an infinite loop.
    By loop count you mean like the 10 you put?

    So how will I add a random number of students? I set it to pick a random number of students, but I think it's creating an Array Index Out of Bounds Exception in my Class class.
    This thing will make sure I'm not adding the same student twice.

    How does a Set work? Does it only have 2 values?

    Why are you making the set an instance of HashSet?

    What is HashSet?

    Did you mean mix.contains()?

  7. #6
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

    package DiscreteMathProject;
     
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.Random;
    import java.util.Set;
     
    public class MainClass {
     
    	private String[] studentNames;
    	private Student[] students;
    	private Class[] classes;
    	private String[] classNames;
    	private ArrayList<Student> aList2;
    	private Random[] random;
     
    	public MainClass()
    	{
    		classes = new Class[20];
    		studentNames = new String[400];
    		students = new Student[400];
    		studentNames[0] = "Joe McDonald";
    		studentNames[1] = "Paul Adcock";
    		studentNames[2] = "Darth Vader";
    		studentNames[3] = "Peter Parker";
    		studentNames[4] = "Abraham Lincoln";
    		studentNames[5] = "Albert Einstein";
    		studentNames[6] = "Spongebob Squarepants";
    		studentNames[7] = "James Bond";
    		studentNames[8] = "Sherlock Holmes";
    		studentNames[9] = "John Wayne";
    		studentNames[10] = "Walter Payton";
    		studentNames[11] = "George Herman (Babe) Ruth";
    		studentNames[12] = "Susan B. Anthony";
    		studentNames[13] = "Martin Luther";
    		studentNames[14] = "Julius Ceasar";
    		studentNames[15] = "Adolf Hitler";
    		studentNames[16] = "Joseph Stalin";
    		studentNames[17] = "Fidel Castro";
    		studentNames[18] = "Ivan The Terrible";
    		studentNames[19] = "Jabba The Hutt";
    		studentNames[20] = "Luke Skywalker";
    		studentNames[21] = "Emperor Palpatine";
    		studentNames[22] = "Thomas Edison";
    		studentNames[23] = "Benjamin Franklin";
    		studentNames[24] = "Judas Iscariot";
    		studentNames[25] = "King David";
    		studentNames[26] = "Blaise Pascal";
    		studentNames[27] = "John Watson";
    		studentNames[28] = "James Watt";
    		studentNames[29] = "Henry Ford";
    		studentNames[30] = "Michael Jackson";
    		studentNames[31] = "Mohatma Ghandi";
    		studentNames[32] = "Emperor Mao";
    		studentNames[33] = "Robin of Locksley (Robin Hood)";
    		studentNames[34] = "King Richard The Lionhearted";
    		studentNames[35] = "Harry Potter";
    		studentNames[36] = "John Smith";
    		studentNames[37] = "King John";
    		studentNames[38] = "William The Conqueror";
    		studentNames[39] = "Bloody Mary";
    		studentNames[40] = "Johnny Cash";
    		studentNames[41] = "Sargon of Akkad";
    		studentNames[42] = "Prince Absalom";
    		studentNames[43] = "Eustace Clarence";
    		studentNames[44] = "Ronald Weasley";
    		studentNames[45] = "Rosa Parks";
    		studentNames[46] = "Sandra Day O'Connor";
    		studentNames[47] = "Queen Lucy Pevensie";
    		studentNames[48] = "John The Apostle";
    		studentNames[49] = "Kevin McAlister";
    		studentNames[50] = "Alex Pruitt";
    		studentNames[51] = "Guy Fawkes";
    		studentNames[52] = "Queen Heshepshut";
    		studentNames[53] = "King Ramases";
    		studentNames[54] = "King Xerxes of Persia";
    		studentNames[55] = "Nathan Hale";
    		studentNames[56] = "Patrick Henry";
    		studentNames[57] = "Jacob Marley";
    		studentNames[58] = "Ebenezer Scrooge";
    		studentNames[59] = "Saint Augustine";
    		studentNames[60] = "John Lennon";
    		studentNames[61] = "Forrest Gump";
    		studentNames[62] = "Jenny Gump";
    		studentNames[63] = "Luitenant Dan";
    		studentNames[64] = "John Q. Public";
    		studentNames[65] = "Bill Gates";
    		studentNames[66] = "Harriet Tubman";
    		studentNames[67] = "Sojourner Truth";
    		studentNames[68] = "Malcom Little(Malcom X)";
    		studentNames[69] = "Leonardo D. Caprio";
    		studentNames[70] = "Jack Philps";
    		studentNames[71] = "Paul Revere";
    		studentNames[72] = "Becky Thatcher";
    		studentNames[73] = "Tom Sawyer";
    		studentNames[74] = "Samual Clemmons(Mark Twain)";
    		studentNames[75] = "George Washington Carver";
    		studentNames[76] = "Paul Bunyan";
    		studentNames[77] = "Huck Finn";
    		studentNames[78] = "Picos Bill";
    		studentNames[79] = "Mark Anthony";
    		studentNames[80] = "Queen Cleopatra";
    		studentNames[81] = "Anne Frank";
    		studentNames[82] = "Eli Wesel";
    		studentNames[83] = "Eddie Brock";
    		studentNames[84] = "Thorin Oakenshield";
    		studentNames[85] = "Bilbo Bagins";
    		studentNames[86] = "Frodo Baggins";
    		studentNames[87] = "Sam Gamagee";
    		studentNames[88] = "Gandalf the Gray";
    		studentNames[89] = "Sauraman the Wise";
    		studentNames[90] = "King George III";
    		studentNames[91] = "William Wilberforce";
    		studentNames[92] = "Merry Brandybuck";
    		studentNames[93] = "Martin Luther King Jr.";
    		studentNames[94] = "Jackie Robinson";
    		studentNames[95] = "Sherwim Williams";
    		studentNames[96] = "John Menard";
    		studentNames[97] = "Chrisopher Columbus";
    		studentNames[98] = "Genghis Khan";
    		studentNames[99] = "Atilla The Hun";
    		studentNames[100] = "Al Capone";
    		studentNames[101] = "Napolean Bonepart";
    		studentNames[102] = "Marie Antionette";
    		studentNames[103] = "King Louis XVII";
    		studentNames[104] = "Napolean Blownapart";
    		studentNames[105] = "Yesser Arafat";
    		studentNames[106] = "Al Gore";
    		studentNames[107] = "Benedict Arnold";
    		studentNames[108] = "Tim Allen";
    		studentNames[109] = "George W. Bush";
    		for (int x = 110; x < 400; x++)
    		{
    			studentNames[x] = "Student " + x;
    		}
     
    		for (int y = 0; y < 400; y++)
    		{
    			students[y] = new Student(studentNames[y]);
    		}
     
    		classNames = new String[20];
     
    		classNames[0] = "Sleeping 101";
    		classNames[1] = "Partying 202";
    		classNames[2] = "Discrete Math";
    		classNames[3] = "Rocket Science";
    		classNames[4] = "Introduction to Data Structures";
    		classNames[5] = "Skipping 303";
    		classNames[6] = "Creative Writing";
    		classNames[7] = "Introduction to Technical Communication";
    		classNames[8] = "Easy Class";
    		classNames[9] = "Surviving College";
    		classNames[10] = "How To Outsmart the Profs";
    		classNames[11] = "Astronomy";
    		classNames[12] = "Thermodynamics";
    		classNames[13] = "Long-winded Lectures 404";
    		classNames[14] = "System Design";
    		classNames[15] = "Physics";
    		classNames[16] = "Chemistry";
    		classNames[17] = "Tutoring";
    		classNames[18] = "Politics 204";
    		classNames[19] = "Very Hard Class";
     
    		for (int z = 0; z < 20; z++)
    		{
    			classes[z] = new Class(classNames[z]);
    		}
     
     
    		Random rand = new Random();
    		Set<Integer> mix = new HashSet<Integer>();
    		for ( int i = 0; i < 10; i++ ){
    		    int rN = rand.nextInt();
    		    while ( mix.contains(rN) ){//already chose
    		        rN = rand.nextInt();//get another
    		    }
    		    mix.add(rN);
    		}
     
     
     
    		for (int k = 0; k < classes[0].getSize()  ; k++)
    		{
    			classes[0].addStudents(students[k]);
    		}
     
    		// System.out.println(classes[0].getName());
    		// System.out.println(students[0].getName());
    		System.out.println(classes[0].toString());
     
    	}
     
    	public static void main(String[] args)
    	{
    		MainClass mainC = new MainClass();
    	}
    }

    package DiscreteMathProject;
     
    import java.util.ArrayList;
    import java.util.Random;
     
    /**
     * @author pradcoc
     *
     */
    public class Class {
     
    	private Student[] students;
    	private String[] times;
    	private String name;
    	private String time;
    	private int size;
    	private Random r,r2;
    	private Random[] random;
    	private ArrayList<Student> aList;
    	private ArrayList<String> aList2;
     
    	public Class(String name)
    	{
     
    		name = this.name;
    		times = new String[10];
    		times[0] = "8:00 a.m.";
    		times[1] = "9:30 a.m.";
    		times[2] = "11:00 a.m.";
    		times[3] = "12:30 p.m.";
    		times[4] = "2:00 p.m.";
    		times[5] = "3:30 p.m.";
    		times[6] = "5:00 p.m.";
    		times[7] = "6:30 p.m.";
    		times[8] = "8:00 p.m.";
    		times[9] = "9:30 p.m.";
    		aList = new ArrayList<Student>();
     
     
    	}
    	public String getTime()
    	{
    		r = new Random();
    		int x = r.nextInt(10);
    		time= times[x];
    		return time;
    	}
     
    	public String getName()
    	{
    		return name;
    	}
     
    	public void addStudents(Student s)
    	{
     
    		aList.add(s);
     
    	}
     
    	public ArrayList<Student> getArrayList()
    	{
    		return aList;
    	}
     
    	public int getSize()
    	{
    	r2 = new Random();
    	int x = r2.nextInt(51);
    	if (x < 13)
    	{
    		x = 13;
    	}
    	size = x;
    	return size;
    	}
     
    	public String toString()
    	{
    		String str = "The class: " + getName() + " is at " + getTime() + "and has " + getSize() + " students." + 
    		" The students in it are: " + getStudentsInClass() + "." ;
    		return str;
    	}
     
    	public String getStudentsInClass()
    	{
    		aList2 = new ArrayList<String>();
    		for (int i = 0; i < getSize(); i++)
    		{
    			aList2.add(aList.get(i).getName());
    		}
     
    		String str = aList2.toString();
    		return str;
    	}
    }

    package DiscreteMathProject;
     
    /**
     * @author pradcoc
     *
     */
    public class Student {
     
    	private String name;
     
    	public Student(String name)
    	{
    		name = this.name;
    	}
     
    	public String getName()
    	{
    		return name;
    	}
     
     
    }

    * @(#)ArrayList.java	1.57 10/03/23
     *
     * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
     * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
     */
     
    package java.util;
     
    /**
     * Resizable-array implementation of the <tt>List</tt> interface.  Implements
     * all optional list operations, and permits all elements, including
     * <tt>null</tt>.  In addition to implementing the <tt>List</tt> interface,
     * this class provides methods to manipulate the size of the array that is
     * used internally to store the list.  (This class is roughly equivalent to
     * <tt>Vector</tt>, except that it is unsynchronized.)<p>
     *
     * The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>,
     * <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant
     * time.  The <tt>add</tt> operation runs in <i>amortized constant time</i>,
     * that is, adding n elements requires O(n) time.  All of the other operations
     * run in linear time (roughly speaking).  The constant factor is low compared
     * to that for the <tt>LinkedList</tt> implementation.<p>
     *
     * Each <tt>ArrayList</tt> instance has a <i>capacity</i>.  The capacity is
     * the size of the array used to store the elements in the list.  It is always
     * at least as large as the list size.  As elements are added to an ArrayList,
     * its capacity grows automatically.  The details of the growth policy are not
     * specified beyond the fact that adding an element has constant amortized
     * time cost.<p>
     *
     * An application can increase the capacity of an <tt>ArrayList</tt> instance
     * before adding a large number of elements using the <tt>ensureCapacity</tt>
     * operation.  This may reduce the amount of incremental reallocation.
     *
     * <p><strong>Note that this implementation is not synchronized.</strong>
     * If multiple threads access an <tt>ArrayList</tt> instance concurrently,
     * and at least one of the threads modifies the list structurally, it
     * <i>must</i> be synchronized externally.  (A structural modification is
     * any operation that adds or deletes one or more elements, or explicitly
     * resizes the backing array; merely setting the value of an element is not
     * a structural modification.)  This is typically accomplished by
     * synchronizing on some object that naturally encapsulates the list.
     *
     * If no such object exists, the list should be "wrapped" using the
     * {@link Collections#synchronizedList Collections.synchronizedList}
     * method.  This is best done at creation time, to prevent accidental
     * unsynchronized access to the list:<pre>
     *   List list = Collections.synchronizedList(new ArrayList(...));</pre>
     *
     * <p>The iterators returned by this class's <tt>iterator</tt> and
     * <tt>listIterator</tt> methods are <i>fail-fast</i>: if the list is
     * structurally modified at any time after the iterator is created, in any way
     * except through the iterator's own <tt>remove</tt> or <tt>add</tt> methods,
     * the iterator will throw a {@link ConcurrentModificationException}.  Thus, in
     * the face of concurrent modification, the iterator fails quickly and cleanly,
     * rather than risking arbitrary, non-deterministic behavior at an undetermined
     * time in the future.<p>
     *
     * Note that the fail-fast behavior of an iterator cannot be guaranteed
     * as it is, generally speaking, impossible to make any hard guarantees in the
     * presence of unsynchronized concurrent modification.  Fail-fast iterators
     * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
     * Therefore, it would be wrong to write a program that depended on this
     * exception for its correctness: <i>the fail-fast behavior of iterators
     * should be used only to detect bugs.</i><p>
     *
     * This class is a member of the
     * <a href="{@docRoot}/../technotes/guides/collections/index.html">
     * Java Collections Framework</a>.
     *
     * @author  Josh Bloch
     * @author  Neal Gafter
     * @version 1.57, 03/23/10
     * @see	    Collection
     * @see	    List
     * @see	    LinkedList
     * @see	    Vector
     * @since   1.2
     */
     
    public class ArrayList<E> extends AbstractList<E>
            implements List<E>, RandomAccess, Cloneable, java.io.Serializable
    {
        private static final long serialVersionUID = 8683452581122892189L;
     
        /**
         * The array buffer into which the elements of the ArrayList are stored.
         * The capacity of the ArrayList is the length of this array buffer.
         */
        private transient Object[] elementData;
     
        /**
         * The size of the ArrayList (the number of elements it contains).
         *
         * @serial
         */
        private int size;
     
        /**
         * Constructs an empty list with the specified initial capacity.
         *
         * @param   initialCapacity   the initial capacity of the list
         * @exception IllegalArgumentException if the specified initial capacity
         *            is negative
         */
        public ArrayList(int initialCapacity) {
    	super();
            if (initialCapacity < 0)
                throw new IllegalArgumentException("Illegal Capacity: "+
                                                   initialCapacity);
    	this.elementData = new Object[initialCapacity];
        }
     
        /**
         * Constructs an empty list with an initial capacity of ten.
         */
        public ArrayList() {
    	this(10);
        }
     
        /**
         * Constructs a list containing the elements of the specified
         * collection, in the order they are returned by the collection's
         * iterator.
         *
         * @param c the collection whose elements are to be placed into this list
         * @throws NullPointerException if the specified collection is null
         */
        public ArrayList(Collection<? extends E> c) {
    	elementData = c.toArray();
    	size = elementData.length;
    	// c.toArray might (incorrectly) not return Object[] (see 6260652)
    	if (elementData.getClass() != Object[].class)
    	    elementData = Arrays.copyOf(elementData, size, Object[].class);
        }
     
        /**
         * Trims the capacity of this <tt>ArrayList</tt> instance to be the
         * list's current size.  An application can use this operation to minimize
         * the storage of an <tt>ArrayList</tt> instance.
         */
        public void trimToSize() {
    	modCount++;
    	int oldCapacity = elementData.length;
    	if (size < oldCapacity) {
                elementData = Arrays.copyOf(elementData, size);
    	}
        }
     
        /**
         * Increases the capacity of this <tt>ArrayList</tt> instance, if
         * necessary, to ensure that it can hold at least the number of elements
         * specified by the minimum capacity argument.
         *
         * @param   minCapacity   the desired minimum capacity
         */
        public void ensureCapacity(int minCapacity) {
    	modCount++;
    	int oldCapacity = elementData.length;
    	if (minCapacity > oldCapacity) {
    	    Object oldData[] = elementData;
    	    int newCapacity = (oldCapacity * 3)/2 + 1;
        	    if (newCapacity < minCapacity)
    		newCapacity = minCapacity;
                // minCapacity is usually close to size, so this is a win:
                elementData = Arrays.copyOf(elementData, newCapacity);
    	}
        }
     
        /**
         * Returns the number of elements in this list.
         *
         * @return the number of elements in this list
         */
        public int size() {
    	return size;
        }
     
        /**
         * Returns <tt>true</tt> if this list contains no elements.
         *
         * @return <tt>true</tt> if this list contains no elements
         */
        public boolean isEmpty() {
    	return size == 0;
        }
     
        /**
         * Returns <tt>true</tt> if this list contains the specified element.
         * More formally, returns <tt>true</tt> if and only if this list contains
         * at least one element <tt>e</tt> such that
         * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
         *
         * @param o element whose presence in this list is to be tested
         * @return <tt>true</tt> if this list contains the specified element
         */
        public boolean contains(Object o) {
    	return indexOf(o) >= 0;
        }
     
        /**
         * Returns the index of the first occurrence of the specified element
         * in this list, or -1 if this list does not contain the element.
         * More formally, returns the lowest index <tt>i</tt> such that
         * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
         * or -1 if there is no such index.
         */
        public int indexOf(Object o) {
    	if (o == null) {
    	    for (int i = 0; i < size; i++)
    		if (elementData[i]==null)
    		    return i;
    	} else {
    	    for (int i = 0; i < size; i++)
    		if (o.equals(elementData[i]))
    		    return i;
    	}
    	return -1;
        }
     
        /**
         * Returns the index of the last occurrence of the specified element
         * in this list, or -1 if this list does not contain the element.
         * More formally, returns the highest index <tt>i</tt> such that
         * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
         * or -1 if there is no such index.
         */
        public int lastIndexOf(Object o) {
    	if (o == null) {
    	    for (int i = size-1; i >= 0; i--)
    		if (elementData[i]==null)
    		    return i;
    	} else {
    	    for (int i = size-1; i >= 0; i--)
    		if (o.equals(elementData[i]))
    		    return i;
    	}
    	return -1;
        }
     
        /**
         * Returns a shallow copy of this <tt>ArrayList</tt> instance.  (The
         * elements themselves are not copied.)
         *
         * @return a clone of this <tt>ArrayList</tt> instance
         */
        public Object clone() {
    	try {
    	    ArrayList<E> v = (ArrayList<E>) super.clone();
    	    v.elementData = Arrays.copyOf(elementData, size);
    	    v.modCount = 0;
    	    return v;
    	} catch (CloneNotSupportedException e) {
    	    // this shouldn't happen, since we are Cloneable
    	    throw new InternalError();
    	}
        }
     
        /**
         * Returns an array containing all of the elements in this list
         * in proper sequence (from first to last element).
         *
         * <p>The returned array will be "safe" in that no references to it are
         * maintained by this list.  (In other words, this method must allocate
         * a new array).  The caller is thus free to modify the returned array.
         *
         * <p>This method acts as bridge between array-based and collection-based
         * APIs.
         *
         * @return an array containing all of the elements in this list in
         *         proper sequence
         */
        public Object[] toArray() {
            return Arrays.copyOf(elementData, size);
        }
     
        /**
         * Returns an array containing all of the elements in this list in proper
         * sequence (from first to last element); the runtime type of the returned
         * array is that of the specified array.  If the list fits in the
         * specified array, it is returned therein.  Otherwise, a new array is
         * allocated with the runtime type of the specified array and the size of
         * this list.
         *
         * <p>If the list fits in the specified array with room to spare
         * (i.e., the array has more elements than the list), the element in
         * the array immediately following the end of the collection is set to
         * <tt>null</tt>.  (This is useful in determining the length of the
         * list <i>only</i> if the caller knows that the list does not contain
         * any null elements.)
         *
         * @param a the array into which the elements of the list are to
         *          be stored, if it is big enough; otherwise, a new array of the
         *          same runtime type is allocated for this purpose.
         * @return an array containing the elements of the list
         * @throws ArrayStoreException if the runtime type of the specified array
         *         is not a supertype of the runtime type of every element in
         *         this list
         * @throws NullPointerException if the specified array is null
         */
        public <T> T[] toArray(T[] a) {
            if (a.length < size)
                // Make a new array of a's runtime type, but my contents:
                return (T[]) Arrays.copyOf(elementData, size, a.getClass());
    	System.arraycopy(elementData, 0, a, 0, size);
            if (a.length > size)
                a[size] = null;
            return a;
        }
     
        // Positional Access Operations
     
        /**
         * Returns the element at the specified position in this list.
         *
         * @param  index index of the element to return
         * @return the element at the specified position in this list
         * @throws IndexOutOfBoundsException {@inheritDoc}
         */
        public E get(int index) {
    	RangeCheck(index);
     
    	return (E) elementData[index];
        }
     
        /**
         * Replaces the element at the specified position in this list with
         * the specified element.
         *
         * @param index index of the element to replace
         * @param element element to be stored at the specified position
         * @return the element previously at the specified position
         * @throws IndexOutOfBoundsException {@inheritDoc}
         */
        public E set(int index, E element) {
    	RangeCheck(index);
     
    	E oldValue = (E) elementData[index];
    	elementData[index] = element;
    	return oldValue;
        }
     
        /**
         * Appends the specified element to the end of this list.
         *
         * @param e element to be appended to this list
         * @return <tt>true</tt> (as specified by {@link Collection#add})
         */
        public boolean add(E e) {
    	ensureCapacity(size + 1);  // Increments modCount!!
    	elementData[size++] = e;
    	return true;
        }
     
        /**
         * Inserts the specified element at the specified position in this
         * list. Shifts the element currently at that position (if any) and
         * any subsequent elements to the right (adds one to their indices).
         *
         * @param index index at which the specified element is to be inserted
         * @param element element to be inserted
         * @throws IndexOutOfBoundsException {@inheritDoc}
         */
        public void add(int index, E element) {
    	if (index > size || index < 0)
    	    throw new IndexOutOfBoundsException(
    		"Index: "+index+", Size: "+size);
     
    	ensureCapacity(size+1);  // Increments modCount!!
    	System.arraycopy(elementData, index, elementData, index + 1,
    			 size - index);
    	elementData[index] = element;
    	size++;
        }
     
        /**
         * Removes the element at the specified position in this list.
         * Shifts any subsequent elements to the left (subtracts one from their
         * indices).
         *
         * @param index the index of the element to be removed
         * @return the element that was removed from the list
         * @throws IndexOutOfBoundsException {@inheritDoc}
         */
        public E remove(int index) {
    	RangeCheck(index);
     
    	modCount++;
    	E oldValue = (E) elementData[index];
     
    	int numMoved = size - index - 1;
    	if (numMoved > 0)
    	    System.arraycopy(elementData, index+1, elementData, index,
    			     numMoved);
    	elementData[--size] = null; // Let gc do its work
     
    	return oldValue;
        }
     
        /**
         * Removes the first occurrence of the specified element from this list,
         * if it is present.  If the list does not contain the element, it is
         * unchanged.  More formally, removes the element with the lowest index
         * <tt>i</tt> such that
         * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
         * (if such an element exists).  Returns <tt>true</tt> if this list
         * contained the specified element (or equivalently, if this list
         * changed as a result of the call).
         *
         * @param o element to be removed from this list, if present
         * @return <tt>true</tt> if this list contained the specified element
         */
        public boolean remove(Object o) {
    	if (o == null) {
                for (int index = 0; index < size; index++)
    		if (elementData[index] == null) {
    		    fastRemove(index);
    		    return true;
    		}
    	} else {
    	    for (int index = 0; index < size; index++)
    		if (o.equals(elementData[index])) {
    		    fastRemove(index);
    		    return true;
    		}
            }
    	return false;
        }
     
        /*
         * Private remove method that skips bounds checking and does not
         * return the value removed.
         */
        private void fastRemove(int index) {
            modCount++;
            int numMoved = size - index - 1;
            if (numMoved > 0)
                System.arraycopy(elementData, index+1, elementData, index,
                                 numMoved);
            elementData[--size] = null; // Let gc do its work
        }
     
        /**
         * Removes all of the elements from this list.  The list will
         * be empty after this call returns.
         */
        public void clear() {
    	modCount++;
     
    	// Let gc do its work
    	for (int i = 0; i < size; i++)
    	    elementData[i] = null;
     
    	size = 0;
        }
     
        /**
         * Appends all of the elements in the specified collection to the end of
         * this list, in the order that they are returned by the
         * specified collection's Iterator.  The behavior of this operation is
         * undefined if the specified collection is modified while the operation
         * is in progress.  (This implies that the behavior of this call is
         * undefined if the specified collection is this list, and this
         * list is nonempty.)
         *
         * @param c collection containing elements to be added to this list
         * @return <tt>true</tt> if this list changed as a result of the call
         * @throws NullPointerException if the specified collection is null
         */
        public boolean addAll(Collection<? extends E> c) {
    	Object[] a = c.toArray();
            int numNew = a.length;
    	ensureCapacity(size + numNew);  // Increments modCount
            System.arraycopy(a, 0, elementData, size, numNew);
            size += numNew;
    	return numNew != 0;
        }
     
        /**
         * Inserts all of the elements in the specified collection into this
         * list, starting at the specified position.  Shifts the element
         * currently at that position (if any) and any subsequent elements to
         * the right (increases their indices).  The new elements will appear
         * in the list in the order that they are returned by the
         * specified collection's iterator.
         *
         * @param index index at which to insert the first element from the
         *              specified collection
         * @param c collection containing elements to be added to this list
         * @return <tt>true</tt> if this list changed as a result of the call
         * @throws IndexOutOfBoundsException {@inheritDoc}
         * @throws NullPointerException if the specified collection is null
         */
        public boolean addAll(int index, Collection<? extends E> c) {
    	if (index > size || index < 0)
    	    throw new IndexOutOfBoundsException(
    		"Index: " + index + ", Size: " + size);
     
    	Object[] a = c.toArray();
    	int numNew = a.length;
    	ensureCapacity(size + numNew);  // Increments modCount
     
    	int numMoved = size - index;
    	if (numMoved > 0)
    	    System.arraycopy(elementData, index, elementData, index + numNew,
    			     numMoved);
     
            System.arraycopy(a, 0, elementData, index, numNew);
    	size += numNew;
    	return numNew != 0;
        }
     
        /**
         * Removes from this list all of the elements whose index is between
         * <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive.
         * Shifts any succeeding elements to the left (reduces their index).
         * This call shortens the list by <tt>(toIndex - fromIndex)</tt> elements.
         * (If <tt>toIndex==fromIndex</tt>, this operation has no effect.)
         *
         * @param fromIndex index of first element to be removed
         * @param toIndex index after last element to be removed
         * @throws IndexOutOfBoundsException if fromIndex or toIndex out of
         *              range (fromIndex &lt; 0 || fromIndex &gt;= size() || toIndex
         *              &gt; size() || toIndex &lt; fromIndex)
         */
        protected void removeRange(int fromIndex, int toIndex) {
    	modCount++;
    	int numMoved = size - toIndex;
            System.arraycopy(elementData, toIndex, elementData, fromIndex,
                             numMoved);
     
    	// Let gc do its work
    	int newSize = size - (toIndex-fromIndex);
    	while (size != newSize)
    	    elementData[--size] = null;
        }
     
        /**
         * Checks if the given index is in range.  If not, throws an appropriate
         * runtime exception.  This method does *not* check if the index is
         * negative: It is always used immediately prior to an array access,
         * which throws an ArrayIndexOutOfBoundsException if index is negative.
         */
        private void RangeCheck(int index) {
    	if (index >= size)
    	    throw new IndexOutOfBoundsException(
    		"Index: "+index+", Size: "+size);
        }
     
        /**
         * Save the state of the <tt>ArrayList</tt> instance to a stream (that
         * is, serialize it).
         *
         * @serialData The length of the array backing the <tt>ArrayList</tt>
         *             instance is emitted (int), followed by all of its elements
         *             (each an <tt>Object</tt>) in the proper order.
         */
        private void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException{
    	// Write out element count, and any hidden stuff
    	int expectedModCount = modCount;
    	s.defaultWriteObject();
     
            // Write out array length
            s.writeInt(elementData.length);
     
    	// Write out all elements in the proper order.
    	for (int i=0; i<size; i++)
                s.writeObject(elementData[i]);
     
    	if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
     
        }
     
        /**
         * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
         * deserialize it).
         */
        private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
    	// Read in size, and any hidden stuff
    	s.defaultReadObject();
     
            // Read in array length and allocate array
            int arrayLength = s.readInt();
            Object[] a = elementData = new Object[arrayLength];
     
    	// Read in all elements in the proper order.
    	for (int i=0; i<size; i++)
                a[i] = s.readObject();
        }
    }
    It sometimes outputs something like:
     The class: null is at 12:30 p.m.and has 44 students. The students in it are: [null, null, null, null, null, null, null, null, null, null, null, null, null, null].

    and other times returns something like:
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 14, Size: 14
    	at java.util.ArrayList.RangeCheck(ArrayList.java:547)
    	at java.util.ArrayList.get(ArrayList.java:322)
    	at DiscreteMathProject.Class.getStudentsInClass(Class.java:93)
    	at DiscreteMathProject.Class.toString(Class.java:84)
    	at DiscreteMathProject.MainClass.<init>(MainClass.java:190)
    	at DiscreteMathProject.MainClass.main(MainClass.java:196)

    It'd be nice to say, I do have a public method that returns the size of the Class. However, I'd like to add that many students, making sure that no student gets added more than once to any class or that any one student ends up in more than 5 classes.

    Also, it'd be nice to have a toString() in the Student class that would return the student's name, the number of classes that he/she is taking, and the names of the classes if possible.

    But I've never been good at reverse adding(I can let the Class know that it has student x but I can't seem to let student x know that he/she is in that class by adding student x to that class. What more should I do? I only have a short time? it's mainly just to help sort something out a whole lot easier for a Discrete Math class. It's not really programming homework.
    Last edited by javapenguin; October 25th, 2010 at 08:19 PM. Reason: I felt like it.

  8. #7
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

     Random rand = new Random();
            Set<Student> mix = new HashSet<Student>();
            Student[] st = new Student[classes[0].getSize()];
            for ( int i = 0; i < classes[0].getSize(); i++ ){
                int rN = rand.nextInt(classes[0].getSize());
                while ( mix.contains(students[rN]) ){//already chose
                    rN = rand.nextInt(classes[0].getSize());//get another
                }
                mix.add(students[rN]);
               mix.toArray(st);
     
              st = mix.toArray(st);
            }
     
     
     
            for (int k = 0; k < classes[0].getSize()  ; k++)
            {
                classes[0].addStudents(st[k]);
            }
     
            // System.out.println(classes[0].getName());
            // System.out.println(students[0].getName());
            System.out.println(classes[0].toString());

    Why isn't the class name, the students' names, and the number of students matching up? I'm thinking maybe because I want the minimum size to be 13 but sometimes it's picking less than that and something is going wrong.

    What's wrong with the getSize() method and the MainClass() where the constructors should be working?

    Why am I getting Array Index Out of Bounds and Null Pointer Exceptions at times?

    Why is pretty much everything except the time and the number of students null?

    Why doesn't the number of students match the number of those in brackets?

    Try 1.) The class: null is at 2:00 p.m.and has 15 students. The students in it are: [null, null, null, null, null, null, null, null, null, null, null, null, null].
    Try 2.) Exception in thread "main" java.lang.NullPointerException
    	at DiscreteMathProject.Class.getStudentsInClass(Class.java:90)
    	at DiscreteMathProject.Class.toString(Class.java:81)
    	at DiscreteMathProject.MainClass.<init>(MainClass.java:194)
    	at DiscreteMathProject.MainClass.main(MainClass.java:200)
    Try 3.) Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 15, Size: 15
    	at java.util.ArrayList.RangeCheck(ArrayList.java:547)
    	at java.util.ArrayList.get(ArrayList.java:322)
    	at DiscreteMathProject.Class.getStudentsInClass(Class.java:90)
    	at DiscreteMathProject.Class.toString(Class.java:81)
    	at DiscreteMathProject.MainClass.<init>(MainClass.java:194)
    	at DiscreteMathProject.MainClass.main(MainClass.java:200)
    Last edited by javapenguin; October 26th, 2010 at 11:49 AM.

  9. #8
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Using Random class

    Hey javapenguin, no one is ignoring you my friend

    I think the questions that contain less code get answered a lot quicker for obvious reasons.

    I will do my best to pick this up tomorrow if no one has got back to you..
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  10. The Following User Says Thank You to JavaPF For This Useful Post:

    javapenguin (October 26th, 2010)

  11. #9
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

    Code has been updated. Now the names will work, but I'm getting Index Out of Bounds and Null Pointer Exceptions still, and the number of students in the brackets and the number of students the the getSize() method is returning aren't usually the same. Also, I'm certain that my getSize() method has some glitch, but what? I'm thinking it's my lower bounds I tried to set but I didn't do it quite properly.

    package DiscreteMathProject;
     
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.Random;
    import java.util.Set;
     
    public class MainClass {
     
        private String[] studentNames;
        private Student[] students;
        private Class[] classes;
        private String[] classNames;
        private ArrayList<Student> aList2;
        private Random[] random;
        PrintWriter outFile;
        public MainClass() throws FileNotFoundException
        {
        	outFile = new PrintWriter("classes.txt");
            classes = new Class[35];
            studentNames = new String[500];
            students = new Student[500];
            studentNames[0] = "Joe McDonald";
            studentNames[1] = "Paul Adcock";
            studentNames[2] = "Darth Vader";
            studentNames[3] = "Peter Parker";
            studentNames[4] = "Abraham Lincoln";
            studentNames[5] = "Albert Einstein";
            studentNames[6] = "Spongebob Squarepants";
            studentNames[7] = "James Bond";
            studentNames[8] = "Sherlock Holmes";
            studentNames[9] = "John Wayne";
            studentNames[10] = "Walter Payton";
            studentNames[11] = "George Herman (Babe) Ruth";
            studentNames[12] = "Susan B. Anthony";
            studentNames[13] = "Martin Luther";
            studentNames[14] = "Julius Ceasar";
            studentNames[15] = "Adolf Hitler";
            studentNames[16] = "Joseph Stalin";
            studentNames[17] = "Fidel Castro";
            studentNames[18] = "Ivan The Terrible";
            studentNames[19] = "Jabba The Hutt";
            studentNames[20] = "Luke Skywalker";
            studentNames[21] = "Emperor Palpatine";
            studentNames[22] = "Thomas Edison";
            studentNames[23] = "Benjamin Franklin";
            studentNames[24] = "Judas Iscariot";
            studentNames[25] = "King David";
            studentNames[26] = "Blaise Pascal";
            studentNames[27] = "John Watson";
            studentNames[28] = "James Watt";
            studentNames[29] = "Henry Ford";
            studentNames[30] = "Michael Jackson";
            studentNames[31] = "Mohatma Ghandi";
            studentNames[32] = "Emperor Mao";
            studentNames[33] = "Robin of Locksley (Robin Hood)";
            studentNames[34] = "King Richard The Lionhearted";
            studentNames[35] = "Harry Potter";
            studentNames[36] = "John Smith";
            studentNames[37] = "King John";
            studentNames[38] = "William The Conqueror";
            studentNames[39] = "Bloody Mary";
            studentNames[40] = "Johnny Cash";
            studentNames[41] = "Sargon of Akkad";
            studentNames[42] = "Prince Absalom";
            studentNames[43] = "Eustace Clarence";
            studentNames[44] = "Ronald Weasley";
            studentNames[45] = "Rosa Parks";
            studentNames[46] = "Sandra Day O'Connor";
            studentNames[47] = "Queen Lucy Pevensie";
            studentNames[48] = "John The Apostle";
            studentNames[49] = "Kevin McAlister";
            studentNames[50] = "Alex Pruitt";
            studentNames[51] = "Guy Fawkes";
            studentNames[52] = "Queen Heshepshut";
            studentNames[53] = "King Ramases";
            studentNames[54] = "King Xerxes of Persia";
            studentNames[55] = "Nathan Hale";
            studentNames[56] = "Patrick Henry";
            studentNames[57] = "Jacob Marley";
            studentNames[58] = "Ebenezer Scrooge";
            studentNames[59] = "Saint Augustine";
            studentNames[60] = "John Lennon";
            studentNames[61] = "Forrest Gump";
            studentNames[62] = "Jenny Gump";
            studentNames[63] = "Luitenant Dan";
            studentNames[64] = "John Q. Public";
            studentNames[65] = "Bill Gates";
            studentNames[66] = "Harriet Tubman";
            studentNames[67] = "Sojourner Truth";
            studentNames[68] = "Malcom Little(Malcom X)";
            studentNames[69] = "Leonardo D. Caprio";
            studentNames[70] = "Jack Philps";
            studentNames[71] = "Paul Revere";
            studentNames[72] = "Becky Thatcher";
            studentNames[73] = "Tom Sawyer";
            studentNames[74] = "Samual Clemmons(Mark Twain)";
            studentNames[75] = "George Washington Carver";
            studentNames[76] = "Paul Bunyan";
            studentNames[77] = "Huck Finn";
            studentNames[78] = "Picos Bill";
            studentNames[79] = "Mark Anthony";
            studentNames[80] = "Queen Cleopatra";
            studentNames[81] = "Anne Frank";
            studentNames[82] = "Eli Wesel";
            studentNames[83] = "Eddie Brock";
            studentNames[84] = "Thorin Oakenshield";
            studentNames[85] = "Bilbo Bagins";
            studentNames[86] = "Frodo Baggins";
            studentNames[87] = "Sam Gamagee";
            studentNames[88] = "Gandalf the Gray";
            studentNames[89] = "Sauraman the Wise";
            studentNames[90] = "King George III";
            studentNames[91] = "William Wilberforce";
            studentNames[92] = "Merry Brandybuck";
            studentNames[93] = "Martin Luther King Jr.";
            studentNames[94] = "Jackie Robinson";
            studentNames[95] = "Sherwim Williams";
            studentNames[96] = "John Menard";
            studentNames[97] = "Chrisopher Columbus";
            studentNames[98] = "Genghis Khan";
            studentNames[99] = "Atilla The Hun";
            studentNames[100] = "Al Capone";
            studentNames[101] = "Napolean Bonepart";
            studentNames[102] = "Marie Antionette";
            studentNames[103] = "King Louis XVII";
            studentNames[104] = "Napolean Blownapart";
            studentNames[105] = "Yesser Arafat";
            studentNames[106] = "Al Gore";
            studentNames[107] = "Benedict Arnold";
            studentNames[108] = "Tim Allen";
            studentNames[109] = "George W. Bush";
            for (int x = 110; x < 500; x++)
            {
                studentNames[x] = "Student " + x;
            }
     
            for (int y = 0; y < 500; y++)
            {
                students[y] = new Student(studentNames[y]);
                students[y].setName(studentNames[y]);
            }
     
            classNames = new String[35];
     
            classNames[0] = "Sleeping 101";
            classNames[1] = "Partying 202";
            classNames[2] = "Discrete Math";
            classNames[3] = "Rocket Science";
            classNames[4] = "Introduction to Data Structures";
            classNames[5] = "Skipping 303";
            classNames[6] = "Creative Writing";
            classNames[7] = "Introduction to Technical Communication";
            classNames[8] = "Easy Class";
            classNames[9] = "Surviving College";
            classNames[10] = "How To Outsmart the Profs";
            classNames[11] = "Astronomy";
            classNames[12] = "Thermodynamics";
            classNames[13] = "Long-winded Lectures 404";
            classNames[14] = "System Design";
            classNames[15] = "Physics";
            classNames[16] = "Chemistry";
            classNames[17] = "Tutoring";
            classNames[18] = "Politics 204";
            classNames[19] = "Very Hard Class";
            classNames[20] = "Introduction to Java Programming";
            classNames[21] = "Biology";
            classNames[22] = "Physical Education";
            classNames[23] = "Databases";
            classNames[24] = "World History";
            classNames[25] = "Philosophy";
            classNames[26] = "Daydreaming 404";
            classNames[27] = "Eating 208";
            classNames[28] = "Kung Fu Fighting";
            classNames[29] = "Religion";
            classNames[30] = "Film Making";
            classNames[31] = "How to Understand Women(Sorta) 467";
            classNames[32] = "How to Understand Men(Sorta) 468";
            classNames[33] = "TV Studio 303";
            classNames[34] = "Architecture";
     
            for (int z = 0; z < 35; z++)
            {
                classes[z] = new Class(classNames[z]);
                classes[z].setName(classNames[z]);
            }
           System.out.println(classes[0].getName());
     
            Random rand = new Random();
            Set<Student> mix = new HashSet<Student>();
            Student[] st = new Student[classes[0].getSize()];
            for ( int i = 0; i < classes[0].getSize(); i++ ){
                int rN = rand.nextInt(classes[0].getSize());
                while ( mix.contains(students[rN]) ){//already chose
                    rN = rand.nextInt(classes[0].getSize());//get another
                }
                mix.add(students[rN]);
               mix.toArray(st);
     
              st = mix.toArray(st);
            }
     
     
     
            for (int k = 0; k < classes[0].getSize()  ; k++)
            {
                classes[0].addStudents(st[k]);
            }
     
            // System.out.println(classes[0].getName());
            // System.out.println(students[0].getName());
            System.out.println(classes[0].toString());
            outFile.println(classes[0].toString());
            outFile.close();
     
            Random rand2 = new Random();
            Set<Student> mix2 = new HashSet<Student>();
            Student[] st2 = new Student[classes[1].getSize()];
            for ( int i2 = 0; i2 < classes[1].getSize(); i2++ ){
                int rN2 = rand.nextInt(classes[1].getSize());
                while ( mix2.contains(students[rN2]) ){//already chose
                    rN2 = rand.nextInt(classes[1].getSize());//get another
                }
                mix2.add(students[rN2]);
               mix2.toArray(st2);
     
              st2 = mix2.toArray(st2);
            }
     
            for (int k2 = 0; k2 < classes[1].getSize()  ; k2++)
            {
                classes[1].addStudents(st2[k2]);
            }
     
            // System.out.println(classes[0].getName());
            // System.out.println(students[0].getName());
            System.out.println(classes[1].toString());
        }
     
        public static void main(String[] args) throws FileNotFoundException
        {
            MainClass mainC = new MainClass();
        }
    }

    package DiscreteMathProject;
     
    /**
     * @author pradcoc
     *
     */
    public class Student {
     
        private String name;
     
        public Student(String name)
        {
            name = this.name;
        }
     
        public String getName()
        {
            return name;
        }
     
        public void setName(String name2)
        {
        	name = name2;
        }
     
     
    }

    package DiscreteMathProject;
     
    import java.util.ArrayList;
    import java.util.Random;
     
    /**
     * @author pradcoc
     *
     */
    public class Class {
     
        private Student[] students;
        private String[] times;
        private String name;
        private String time;
        private int size;
        private Random r,r2;
        private Random[] random;
        private ArrayList<Student> aList;
        private ArrayList<String> aList2;
     
        public Class(String name)
        {
     
            name = this.name;
            times = new String[10];
            times[0] = "8:00 a.m.";
            times[1] = "9:30 a.m.";
            times[2] = "11:00 a.m.";
            times[3] = "12:30 p.m.";
            times[4] = "2:00 p.m.";
            times[5] = "3:30 p.m.";
            times[6] = "5:00 p.m.";
            times[7] = "6:30 p.m.";
            times[8] = "8:00 p.m.";
            times[9] = "9:30 p.m.";
            aList = new ArrayList<Student>();
     
     
        }
        public String getTime()
        {
            r = new Random();
            int x = r.nextInt(10);
            time= times[x];
            return time;
        }
     
        public String getName()
        {
            return name;
        }
     
        public void setName(String name2)
        {
        	name = name2;
        }
     
        public void addStudents(Student s)
        {
     
            aList.add(s);
     
        }
     
        public ArrayList<Student> getArrayList()
        {
            return aList;
        }
     
        public int getSize()
        {
        r2 = new Random();
     
        int x = r2.nextInt(26);
        if (x < 15)
        {
            x = 15;
            size = x;
            return size;
        }
     
     
        else
        {
        size = x;
        return size;
        }
        }
     
        public String toString()
        {
            String str = "The class: " + getName() + " is at " + getTime() + "and has " + getSize() + " students." +
            " The students in it are: " + getStudentsInClass() + "." ;
            return str;
        }
     
        public String getStudentsInClass()
        {
            aList2 = new ArrayList<String>();
            for (int i = 0; i < getSize(); i++)
            {
                aList2.add(aList.get(i).getName());
            }
     
            String str = aList2.toString();
            return str;
        }
    }

  12. #10
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

    I still haven't gotten this part solved, and I'm having problems using UNIX now for something else and am kind of busy at the moment.

  13. #11
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Using Random class

    I'm taking a look at this now.. Trying to figure out the issue.
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  14. The Following User Says Thank You to JavaPF For This Useful Post:

    javapenguin (October 28th, 2010)

  15. #12
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

    Well, I should have the set methods called in the constructors to avoid having to call them in the for loops.

    Also, it's my getSize() method. Something is wrong there. Why is it going out of bounds?

    Also, it'd be nice if each Student knows how many Class(es) it has and what those Class(es) are. Also, so that each Student could be in no more than 7 Class(es).

    Well, I could always have another ArrayList<Class> that will take care of letting a Student know how many Class(es) it has.

    It could also try to make sure that that ArrayList<Class> has no more than seven elements. However, I'd also like to make sure it doesn't have a Student in a class 2 or more times. The Class class has an ArrayList<Student> that makes sure that a Student isn't in a Class twice or more, but how do I get the Student to make sure that in the list of Class(es) that it doesn't have the same Class appearing twice or more?

    The tricky part is to make sure that the two ArrayLists correspond with the correct values and don't contradict each other.

  16. #13
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

    package DiscreteMathProject;
     
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.Random;
    import java.util.Set;
     
    public class MainClass {
     
        private String[] studentNames;
        private Student[] students;
        private Class[] classes;
        private String[] classNames;
        private ArrayList<Student> aList2;
        private Random[] random;
        PrintWriter outFile;
        public MainClass() throws FileNotFoundException
        {
        	outFile = new PrintWriter("classes.txt");
            classes = new Class[35];
            studentNames = new String[500];
            students = new Student[500];
            studentNames[0] = "Joe McDonald";
            studentNames[1] = "Paul Adcock";
            studentNames[2] = "Darth Vader";
            studentNames[3] = "Peter Parker";
            studentNames[4] = "Abraham Lincoln";
            studentNames[5] = "Albert Einstein";
            studentNames[6] = "Spongebob Squarepants";
            studentNames[7] = "James Bond";
            studentNames[8] = "Sherlock Holmes";
            studentNames[9] = "John Wayne";
            studentNames[10] = "Walter Payton";
            studentNames[11] = "George Herman (Babe) Ruth";
            studentNames[12] = "Susan B. Anthony";
            studentNames[13] = "Martin Luther";
            studentNames[14] = "Julius Ceasar";
            studentNames[15] = "Adolf Hitler";
            studentNames[16] = "Joseph Stalin";
            studentNames[17] = "Fidel Castro";
            studentNames[18] = "Ivan The Terrible";
            studentNames[19] = "Jabba The Hutt";
            studentNames[20] = "Luke Skywalker";
            studentNames[21] = "Emperor Palpatine";
            studentNames[22] = "Thomas Edison";
            studentNames[23] = "Benjamin Franklin";
            studentNames[24] = "Judas Iscariot";
            studentNames[25] = "King David";
            studentNames[26] = "Blaise Pascal";
            studentNames[27] = "John Watson";
            studentNames[28] = "James Watt";
            studentNames[29] = "Henry Ford";
            studentNames[30] = "Michael Jackson";
            studentNames[31] = "Mohatma Ghandi";
            studentNames[32] = "Emperor Mao";
            studentNames[33] = "Robin of Locksley (Robin Hood)";
            studentNames[34] = "King Richard The Lionhearted";
            studentNames[35] = "Harry Potter";
            studentNames[36] = "John Smith";
            studentNames[37] = "King John";
            studentNames[38] = "William The Conqueror";
            studentNames[39] = "Bloody Mary";
            studentNames[40] = "Johnny Cash";
            studentNames[41] = "Sargon of Akkad";
            studentNames[42] = "Prince Absalom";
            studentNames[43] = "Eustace Clarence";
            studentNames[44] = "Ronald Weasley";
            studentNames[45] = "Rosa Parks";
            studentNames[46] = "Sandra Day O'Connor";
            studentNames[47] = "Queen Lucy Pevensie";
            studentNames[48] = "John The Apostle";
            studentNames[49] = "Kevin McAlister";
            studentNames[50] = "Alex Pruitt";
            studentNames[51] = "Guy Fawkes";
            studentNames[52] = "Queen Heshepshut";
            studentNames[53] = "King Ramases";
            studentNames[54] = "King Xerxes of Persia";
            studentNames[55] = "Nathan Hale";
            studentNames[56] = "Patrick Henry";
            studentNames[57] = "Jacob Marley";
            studentNames[58] = "Ebenezer Scrooge";
            studentNames[59] = "Saint Augustine";
            studentNames[60] = "John Lennon";
            studentNames[61] = "Forrest Gump";
            studentNames[62] = "Jenny Gump";
            studentNames[63] = "Luitenant Dan";
            studentNames[64] = "John Q. Public";
            studentNames[65] = "Bill Gates";
            studentNames[66] = "Harriet Tubman";
            studentNames[67] = "Sojourner Truth";
            studentNames[68] = "Malcom Little(Malcom X)";
            studentNames[69] = "Leonardo D. Caprio";
            studentNames[70] = "Jack Philps";
            studentNames[71] = "Paul Revere";
            studentNames[72] = "Becky Thatcher";
            studentNames[73] = "Tom Sawyer";
            studentNames[74] = "Samual Clemmons(Mark Twain)";
            studentNames[75] = "George Washington Carver";
            studentNames[76] = "Paul Bunyan";
            studentNames[77] = "Huck Finn";
            studentNames[78] = "Picos Bill";
            studentNames[79] = "Mark Anthony";
            studentNames[80] = "Queen Cleopatra";
            studentNames[81] = "Anne Frank";
            studentNames[82] = "Eli Wesel";
            studentNames[83] = "Eddie Brock";
            studentNames[84] = "Thorin Oakenshield";
            studentNames[85] = "Bilbo Bagins";
            studentNames[86] = "Frodo Baggins";
            studentNames[87] = "Sam Gamagee";
            studentNames[88] = "Gandalf the Gray";
            studentNames[89] = "Sauraman the Wise";
            studentNames[90] = "King George III";
            studentNames[91] = "William Wilberforce";
            studentNames[92] = "Merry Brandybuck";
            studentNames[93] = "Martin Luther King Jr.";
            studentNames[94] = "Jackie Robinson";
            studentNames[95] = "Sherwim Williams";
            studentNames[96] = "John Menard";
            studentNames[97] = "Chrisopher Columbus";
            studentNames[98] = "Genghis Khan";
            studentNames[99] = "Atilla The Hun";
            studentNames[100] = "Al Capone";
            studentNames[101] = "Napolean Bonepart";
            studentNames[102] = "Marie Antionette";
            studentNames[103] = "King Louis XVII";
            studentNames[104] = "Napolean Blownapart";
            studentNames[105] = "Yesser Arafat";
            studentNames[106] = "Al Gore";
            studentNames[107] = "Benedict Arnold";
            studentNames[108] = "Tim Allen";
            studentNames[109] = "George W. Bush";
            for (int x = 110; x < 500; x++)
            {
                studentNames[x] = "Student " + x;
            }
     
            for (int y = 0; y < 500; y++)
            {
                students[y] = new Student(studentNames[y]);
     
            }
     
            classNames = new String[35];
     
            classNames[0] = "Sleeping 101";
            classNames[1] = "Partying 202";
            classNames[2] = "Discrete Math";
            classNames[3] = "Rocket Science";
            classNames[4] = "Introduction to Data Structures";
            classNames[5] = "Skipping 303";
            classNames[6] = "Creative Writing";
            classNames[7] = "Introduction to Technical Communication";
            classNames[8] = "Easy Class";
            classNames[9] = "Surviving College";
            classNames[10] = "How To Outsmart the Profs";
            classNames[11] = "Astronomy";
            classNames[12] = "Thermodynamics";
            classNames[13] = "Long-winded Lectures 404";
            classNames[14] = "System Design";
            classNames[15] = "Physics";
            classNames[16] = "Chemistry";
            classNames[17] = "Tutoring";
            classNames[18] = "Politics 204";
            classNames[19] = "Very Hard Class";
            classNames[20] = "Introduction to Java Programming";
            classNames[21] = "Biology";
            classNames[22] = "Physical Education";
            classNames[23] = "Databases";
            classNames[24] = "World History";
            classNames[25] = "Philosophy";
            classNames[26] = "Daydreaming 404";
            classNames[27] = "Eating 208";
            classNames[28] = "Kung Fu Fighting";
            classNames[29] = "Religion";
            classNames[30] = "Film Making";
            classNames[31] = "How to Understand Women(Sorta) 467";
            classNames[32] = "How to Understand Men(Sorta) 468";
            classNames[33] = "TV Studio 303";
            classNames[34] = "Architecture";
     
            for (int z = 0; z < 35; z++)
            {
                classes[z] = new Class(classNames[z]);
     
            }
           System.out.println(classes[0].getName());
     
            Random rand = new Random();
            Set<Student> mix = new HashSet<Student>();
            Student[] st = new Student[classes[0].getSize()];
            for ( int i = 0; i < classes[0].getSize(); i++ ){
                int rN = rand.nextInt(classes[0].getSize());
                while ( mix.contains(students[rN]) ){//already chose
                    rN = rand.nextInt(classes[0].getSize());//get another
                }
                mix.add(students[rN]);
               mix.toArray(st);
     
              st = mix.toArray(st);
            }
     
     
     
            for (int k = 0; k < classes[0].getSize()  ; k++)
            {
                classes[0].addStudents(st[k]);
            }
     
            // System.out.println(classes[0].getName());
            // System.out.println(students[0].getName());
            System.out.println(classes[0].toString());
            outFile.println(classes[0].toString());
            outFile.close();
     
            Random rand2 = new Random();
            Set<Student> mix2 = new HashSet<Student>();
            Student[] st2 = new Student[classes[1].getSize()];
            for ( int i2 = 0; i2 < classes[1].getSize(); i2++ ){
                int rN2 = rand.nextInt(classes[1].getSize());
                while ( mix2.contains(students[rN2]) ){//already chose
                    rN2 = rand.nextInt(classes[1].getSize());//get another
                }
                mix2.add(students[rN2]);
               mix2.toArray(st2);
     
              st2 = mix2.toArray(st2);
            }
     
            for (int k2 = 0; k2 < classes[1].getSize()  ; k2++)
            {
                classes[1].addStudents(st2[k2]);
            }
     
            // System.out.println(classes[0].getName());
            // System.out.println(students[0].getName());
            System.out.println(classes[1].toString());
        }
     
        public static void main(String[] args) throws FileNotFoundException
        {
            MainClass mainC = new MainClass();
        }
    }

    package DiscreteMathProject;
     
    /**
     * @author pradcoc
     *
     */
    public class Student {
     
        private String name;
        private int numOfClasses;
        private ArrayList<Class> aList;
        private ArrayList<String> aList2;
     
        public Student(String name)
        {
     
            name = this.name;
             setName(name);
        }
     
        public String getName()
        {
            return name;
        }
     
        public void setName(String name2)
        {
        	name = name2;
        }
     
       public void addClasses(Class c)
    {
    aList.add(c);
    }
     
    public String getClasses()
    {
    for (int i = 0; i < aList.size(); i++)
            {
                aList2.add(aList.get(i).getName());
            }
     
            String str = aList2.toString();
            return str;
     
    }
     
    public int getNumOfClasses()
    {
    numOfClasses = aList2.size();
    return numOfClasses;
    }
     
    public String toString()
    {
    String str = "The student's name is: " + getName() + ".  The student is in " + getNumOfClasses() + " classes.  The classes are " + getClasses() + ".";
    return str;
    }
     
    }

    package DiscreteMathProject;
     
    import java.util.ArrayList;
    import java.util.Random;
     
    /**
     * @author pradcoc
     *
     */
    public class Class {
     
        private Student[] students;
        private String[] times;
        private String name;
        private String time;
        private int size;
        private Random r,r2;
        private Random[] random;
        private ArrayList<Student> aList;
        private ArrayList<String> aList2;
     
        public Class(String name)
        {
     
            name = this.name;
            times = new String[10];
            times[0] = "8:00 a.m.";
            times[1] = "9:30 a.m.";
            times[2] = "11:00 a.m.";
            times[3] = "12:30 p.m.";
            times[4] = "2:00 p.m.";
            times[5] = "3:30 p.m.";
            times[6] = "5:00 p.m.";
            times[7] = "6:30 p.m.";
            times[8] = "8:00 p.m.";
            times[9] = "9:30 p.m.";
            aList = new ArrayList<Student>();
       aList2 = new ArrayList<String>();
          setName(name);
     
     
        }
        public String getTime()
        {
            r = new Random();
            int x = r.nextInt(10);
            time= times[x];
            return time;
        }
     
        public String getName()
        {
            return name;
        }
     
        public void setName(String name2)
        {
        	name = name2;
        }
     
        public void addStudents(Student s)
        {
     
            aList.add(s);
     
        }
     
        public ArrayList<Student> getArrayList()
        {
            return aList;
        }
     
        public int getSize()
        {
        r2 = new Random();
     
        int x = r2.nextInt(26);
        if (x < 15)
        {
            x = 15;
            size = x;
            return size;
        }
     
     
        else
        {
        size = x;
        return size;
        }
        }
     
        public String toString()
        {
            String str = "The class: " + getName() + " is at " + getTime() + "and has " + getSize() + " students." +
            " The students in it are: " + getStudentsInClass() + "." ;
            return str;
        }
     
        public String getStudentsInClass()
        {
     
            for (int i = 0; i < getSize(); i++)
            {
                aList2.add(aList.get(i).getName());
            }
     
            String str = aList2.toString();
            return str;
        }
    }
    Last edited by javapenguin; October 28th, 2010 at 04:16 PM.

  17. #14
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

    Well, what's wrong with the getSize() method?

  18. #15
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

    package DiscreteMathProject;
     
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.Random;
    import java.util.Set;
     
    public class MainClass {
     
        private String[] studentNames;
        private Student[] students;
        private Class[] classes;
        private String[] classNames;
        private ArrayList<Student> aList2;
        private Random[] random;
        PrintWriter outFile;
        public MainClass() throws FileNotFoundException
        {
        	outFile = new PrintWriter("classes.txt");
            classes = new Class[35];
            studentNames = new String[500];
            students = new Student[500];
            studentNames[0] = "Joe McDonald";
            studentNames[1] = "Paul Adcock";
            studentNames[2] = "Darth Vader";
            studentNames[3] = "Peter Parker";
            studentNames[4] = "Abraham Lincoln";
            studentNames[5] = "Albert Einstein";
            studentNames[6] = "Spongebob Squarepants";
            studentNames[7] = "James Bond";
            studentNames[8] = "Sherlock Holmes";
            studentNames[9] = "John Wayne";
            studentNames[10] = "Walter Payton";
            studentNames[11] = "George Herman (Babe) Ruth";
            studentNames[12] = "Susan B. Anthony";
            studentNames[13] = "Martin Luther";
            studentNames[14] = "Julius Ceasar";
            studentNames[15] = "Adolf Hitler";
            studentNames[16] = "Joseph Stalin";
            studentNames[17] = "Fidel Castro";
            studentNames[18] = "Ivan The Terrible";
            studentNames[19] = "Jabba The Hutt";
            studentNames[20] = "Luke Skywalker";
            studentNames[21] = "Emperor Palpatine";
            studentNames[22] = "Thomas Edison";
            studentNames[23] = "Benjamin Franklin";
            studentNames[24] = "Judas Iscariot";
            studentNames[25] = "King David";
            studentNames[26] = "Blaise Pascal";
            studentNames[27] = "John Watson";
            studentNames[28] = "James Watt";
            studentNames[29] = "Henry Ford";
            studentNames[30] = "Michael Jackson";
            studentNames[31] = "Mohatma Ghandi";
            studentNames[32] = "Emperor Mao";
            studentNames[33] = "Robin of Locksley (Robin Hood)";
            studentNames[34] = "King Richard The Lionhearted";
            studentNames[35] = "Harry Potter";
            studentNames[36] = "John Smith";
            studentNames[37] = "King John";
            studentNames[38] = "William The Conqueror";
            studentNames[39] = "Bloody Mary";
            studentNames[40] = "Johnny Cash";
            studentNames[41] = "Sargon of Akkad";
            studentNames[42] = "Prince Absalom";
            studentNames[43] = "Eustace Clarence";
            studentNames[44] = "Ronald Weasley";
            studentNames[45] = "Rosa Parks";
            studentNames[46] = "Sandra Day O'Connor";
            studentNames[47] = "Queen Lucy Pevensie";
            studentNames[48] = "John The Apostle";
            studentNames[49] = "Kevin McAlister";
            studentNames[50] = "Alex Pruitt";
            studentNames[51] = "Guy Fawkes";
            studentNames[52] = "Queen Heshepshut";
            studentNames[53] = "King Ramases";
            studentNames[54] = "King Xerxes of Persia";
            studentNames[55] = "Nathan Hale";
            studentNames[56] = "Patrick Henry";
            studentNames[57] = "Jacob Marley";
            studentNames[58] = "Ebenezer Scrooge";
            studentNames[59] = "Saint Augustine";
            studentNames[60] = "John Lennon";
            studentNames[61] = "Forrest Gump";
            studentNames[62] = "Jenny Gump";
            studentNames[63] = "Luitenant Dan";
            studentNames[64] = "John Q. Public";
            studentNames[65] = "Bill Gates";
            studentNames[66] = "Harriet Tubman";
            studentNames[67] = "Sojourner Truth";
            studentNames[68] = "Malcom Little(Malcom X)";
            studentNames[69] = "Leonardo D. Caprio";
            studentNames[70] = "Jack Philps";
            studentNames[71] = "Paul Revere";
            studentNames[72] = "Becky Thatcher";
            studentNames[73] = "Tom Sawyer";
            studentNames[74] = "Samual Clemmons(Mark Twain)";
            studentNames[75] = "George Washington Carver";
            studentNames[76] = "Paul Bunyan";
            studentNames[77] = "Huck Finn";
            studentNames[78] = "Picos Bill";
            studentNames[79] = "Mark Anthony";
            studentNames[80] = "Queen Cleopatra";
            studentNames[81] = "Anne Frank";
            studentNames[82] = "Eli Wesel";
            studentNames[83] = "Eddie Brock";
            studentNames[84] = "Thorin Oakenshield";
            studentNames[85] = "Bilbo Bagins";
            studentNames[86] = "Frodo Baggins";
            studentNames[87] = "Sam Gamagee";
            studentNames[88] = "Gandalf the Gray";
            studentNames[89] = "Sauraman the Wise";
            studentNames[90] = "King George III";
            studentNames[91] = "William Wilberforce";
            studentNames[92] = "Merry Brandybuck";
            studentNames[93] = "Martin Luther King Jr.";
            studentNames[94] = "Jackie Robinson";
            studentNames[95] = "Sherwim Williams";
            studentNames[96] = "John Menard";
            studentNames[97] = "Chrisopher Columbus";
            studentNames[98] = "Genghis Khan";
            studentNames[99] = "Atilla The Hun";
            studentNames[100] = "Al Capone";
            studentNames[101] = "Napolean Bonepart";
            studentNames[102] = "Marie Antionette";
            studentNames[103] = "King Louis XVII";
            studentNames[104] = "Napolean Blownapart";
            studentNames[105] = "Yesser Arafat";
            studentNames[106] = "Al Gore";
            studentNames[107] = "Benedict Arnold";
            studentNames[108] = "Tim Allen";
            studentNames[109] = "George W. Bush";
            for (int x = 110; x < 500; x++)
            {
                studentNames[x] = "Student " + x;
            }
     
            for (int y = 0; y < 500; y++)
            {
                students[y] = new Student(studentNames[y]);
     
            }
     
            classNames = new String[35];
     
            classNames[0] = "Sleeping 101";
            classNames[1] = "Partying 202";
            classNames[2] = "Discrete Math";
            classNames[3] = "Rocket Science";
            classNames[4] = "Introduction to Data Structures";
            classNames[5] = "Skipping 303";
            classNames[6] = "Creative Writing";
            classNames[7] = "Introduction to Technical Communication";
            classNames[8] = "Easy Class";
            classNames[9] = "Surviving College";
            classNames[10] = "How To Outsmart the Profs";
            classNames[11] = "Astronomy";
            classNames[12] = "Thermodynamics";
            classNames[13] = "Long-winded Lectures 404";
            classNames[14] = "System Design";
            classNames[15] = "Physics";
            classNames[16] = "Chemistry";
            classNames[17] = "Tutoring";
            classNames[18] = "Politics 204";
            classNames[19] = "Very Hard Class";
            classNames[20] = "Introduction to Java Programming";
            classNames[21] = "Biology";
            classNames[22] = "Physical Education";
            classNames[23] = "Databases";
            classNames[24] = "World History";
            classNames[25] = "Philosophy";
            classNames[26] = "Daydreaming 404";
            classNames[27] = "Eating 208";
            classNames[28] = "Kung Fu Fighting";
            classNames[29] = "Religion";
            classNames[30] = "Film Making";
            classNames[31] = "How to Understand Women(Sorta) 467";
            classNames[32] = "How to Understand Men(Sorta) 468";
            classNames[33] = "TV Studio 303";
            classNames[34] = "Architecture";
     
            for (int z = 0; z < 35; z++)
            {
                classes[z] = new Class(classNames[z]);
     
            }
           System.out.println(classes[0].getName());
     
            Random rand = new Random();
            Set<Student> mix = new HashSet<Student>();
            Student[] st = new Student[classes[0].getSize()];
            for ( int i = 0; i < classes[0].getSize(); i++ ){
                int rN = rand.nextInt(classes[0].getSize());
                while ( mix.contains(students[rN]) ){//already chose
                    rN = rand.nextInt(classes[0].getSize());//get another
                }
                mix.add(students[rN]);
               mix.toArray(st);
     
              st = mix.toArray(st);
            }
     
     
     
            for (int k = 0; k < classes[0].getSize()  ; k++)
            {
                classes[0].addStudents(st[k]);
            }
     
            // System.out.println(classes[0].getName());
            // System.out.println(students[0].getName());
            System.out.println(classes[0].toString());
            outFile.println(classes[0].toString());
            outFile.close();
     
            Random rand2 = new Random();
            Set<Student> mix2 = new HashSet<Student>();
            Student[] st2 = new Student[classes[1].getSize()];
            for ( int i2 = 0; i2 < classes[1].getSize(); i2++ ){
                int rN2 = rand.nextInt(classes[1].getSize());
                while ( mix2.contains(students[rN2]) ){//already chose
                    rN2 = rand.nextInt(classes[1].getSize());//get another
                }
                mix2.add(students[rN2]);
               mix2.toArray(st2);
     
              st2 = mix2.toArray(st2);
            }
     
            for (int k2 = 0; k2 < classes[1].getSize()  ; k2++)
            {
                classes[1].addStudents(st2[k2]);
            }
     
            // System.out.println(classes[0].getName());
            // System.out.println(students[0].getName());
            System.out.println(classes[1].toString());
        }
     
        public static void main(String[] args) throws FileNotFoundException
        {
            MainClass mainC = new MainClass();
        }
    }

    package DiscreteMathProject;
     
    /**
     * @author pradcoc
     *
     */
    public class Student {
     
        private String name;
        private int numOfClasses;
        private ArrayList<Class> aList;
        private ArrayList<String> aList2;
     
        public Student(String name)
        {
     
            name = this.name;
             setName(name);
        }
     
        public String getName()
        {
            return name;
        }
     
        public void setName(String name2)
        {
        	name = name2;
        }
     
       public void addClasses(Class c)
    {
    aList.add(c);
    }
     
    public String getClasses()
    {
    for (int i = 0; i < aList.size(); i++)
            {
                aList2.add(aList.get(i).getName());
            }
     
            String str = aList2.toString();
            return str;
     
    }
     
    public int getNumOfClasses()
    {
    numOfClasses = aList2.size();
    return numOfClasses;
    }
     
    public String toString()
    {
    String str = "The student's name is: " + getName() + ".  The student is in " + getNumOfClasses() + " classes.  The classes are " + getClasses() + ".";
    return str;
    }
     
    }

    package DiscreteMathProject;
     
    import java.util.ArrayList;
    import java.util.Random;
     
    /**
     * @author pradcoc
     *
     */
    public class Class {
     
        private Student[] students;
        private String[] times;
        private String name;
        private String time;
        private int size;
        private Random r,r2;
        private Random[] random;
        private ArrayList<Student> aList;
        private ArrayList<String> aList2;
     
        public Class(String name)
        {
     
            name = this.name;
            times = new String[10];
            times[0] = "8:00 a.m.";
            times[1] = "9:30 a.m.";
            times[2] = "11:00 a.m.";
            times[3] = "12:30 p.m.";
            times[4] = "2:00 p.m.";
            times[5] = "3:30 p.m.";
            times[6] = "5:00 p.m.";
            times[7] = "6:30 p.m.";
            times[8] = "8:00 p.m.";
            times[9] = "9:30 p.m.";
            aList = new ArrayList<Student>();
       aList2 = new ArrayList<String>();
          setName(name);
     
     
        }
        public String getTime()
        {
            r = new Random();
            int x = r.nextInt(10);
            time= times[x];
            return time;
        }
     
        public String getName()
        {
            return name;
        }
     
        public void setName(String name2)
        {
        	name = name2;
        }
     
        public void addStudents(Student s)
        {
     
            aList.add(s);
     
        }
     
        public ArrayList<Student> getArrayList()
        {
            return aList;
        }
     
        public int getSize()
        {
        r2 = new Random();
     
        int x = r2.nextInt(26);
        if (x < 15)
        {
            x = 15;
            size = x;
            return size;
        }
     
     
        else
        {
        size = x;
        return size;
        }
        }
     
        public String toString()
        {
            String str = "The class: " + getName() + " is at " + getTime() + "and has " + getSize() + " students." +
            " The students in it are: " + getStudentsInClass() + "." ;
            return str;
        }
     
        public String getStudentsInClass()
        {
     
            for (int i = 0; i < getSize(); i++)
            {
                aList2.add(aList.get(i).getName());
            }
     
            String str = aList2.toString();
            return str;
        }
     
    public ArrayList<String> getStudentsInClass2()
    {
    return aList2;
    }
    }

    Am thinking of making the HashSet a TreeSet and getting the names and class names in alphabetical order.

    How do I do that? Just learned TreeSets today.

    Also, I'd like to have a method:

    public boolean isAdjacent(TreeSet< students in class1> ts1, TreeSet<Students in  class2> ts2)
    {
    if (the intersection of the TreeSet of Students in class 1 has 1 or more students in common with the TreeSet of students in class 2)
    return true;
     
    else
    return false;
     
    }
    and some more methods
     
    public boolean canBeAtSameTime(TreeSet< students in class1> ts1, TreeSet<Students in  class2> ts2)
    {
     
    if(!isAdjacent(ts1,ts2))
    {
    return true;
    }
     
    else
    return false;
    }
     
    public boolean isConnectedGraph(Class[] arrayOfClasses)
    {
     
    // use for loop to check for every class, to see if it is adjacent with at least 1 other class.
     
    // if any are only adjacent with themselves, return false
     
    // if all are adjacent with at least 1 other class, return true
     
    // to be adjacent, a class must have at least 1 student in common 
     
    }
     
     
    public ArrayList (Class class1, Class class2)
    {
    if (this.canBeAtSameTime(class1,class2))
    // make an array list or a set or a treeset that has students in both classes.
     
    return (theArrayListOrSetOrTreeSet);
     
    }
     
    // in the event that this method returns true, which it probably almost always won't, then 
    // I'll know that the maximum number of colors I need, a.k.a. the maximum number of exam times
    // will be 35.  
    public boolean isCompleteGraph(Class[] arrayOfClasses)
    {
    // if for every class, it is adjacent to every other class, then return true
     
    // else return false
     
    }


    Also,

     
    public class Vertex
    {
     
    private ArrayList<String> students2;
    private Class aClass;
    private String students;
     
    public Vertex(Class a)
    {
    students = aClass.getStudentsInClass();
    students2 = aClass.getStudentsInClass2();
    }
     
    }

    public class Background extends JFrame
    {
    private JPanel panel;
    private JScrollPane pane;
     
    public Background()
    {
    setTitle("Background");
    panel = new JPanel();
    pane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLL_BAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLL_BAR_AS_NEEDED);
    panel.setVisible(true);
    pane.setVisible(true);
     
    setContentPane(pane);
    }
     
    public static void main(String[] args)
    {
    Background b = new Background();
    }
     
    public void paint(Graphics g)
    {
    super();
     
    }
    }
    Last edited by javapenguin; November 4th, 2010 at 04:31 PM.

  19. #16
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Cool Re: Using Random class

    package DiscreteMathProject;
     
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.Random;
    import java.util.Set;
     
    public class MainClass {
     
        private String[] studentNames;
        private Student[] students;
        private Class[] classes;
        private String[] classNames;
        private ArrayList<Student> aList2;
        private Random[] random;
        PrintWriter outFile;
        public MainClass() throws FileNotFoundException
        {
        	outFile = new PrintWriter("classes.txt");
            classes = new Class[35];
            studentNames = new String[500];
            students = new Student[500];
            studentNames[0] = "Joe McDonald";
            studentNames[1] = "Paul Adcock";
            studentNames[2] = "Darth Vader";
            studentNames[3] = "Peter Parker";
            studentNames[4] = "Abraham Lincoln";
            studentNames[5] = "Albert Einstein";
            studentNames[6] = "Spongebob Squarepants";
            studentNames[7] = "James Bond";
            studentNames[8] = "Sherlock Holmes";
            studentNames[9] = "John Wayne";
            studentNames[10] = "Walter Payton";
            studentNames[11] = "George Herman (Babe) Ruth";
            studentNames[12] = "Susan B. Anthony";
            studentNames[13] = "Martin Luther";
            studentNames[14] = "Julius Ceasar";
            studentNames[15] = "Adolf Hitler";
            studentNames[16] = "Joseph Stalin";
            studentNames[17] = "Fidel Castro";
            studentNames[18] = "Ivan The Terrible";
            studentNames[19] = "Jabba The Hutt";
            studentNames[20] = "Luke Skywalker";
            studentNames[21] = "Emperor Palpatine";
            studentNames[22] = "Thomas Edison";
            studentNames[23] = "Benjamin Franklin";
            studentNames[24] = "Judas Iscariot";
            studentNames[25] = "King David";
            studentNames[26] = "Blaise Pascal";
            studentNames[27] = "John Watson";
            studentNames[28] = "James Watt";
            studentNames[29] = "Henry Ford";
            studentNames[30] = "Michael Jackson";
            studentNames[31] = "Mohatma Ghandi";
            studentNames[32] = "Emperor Mao";
            studentNames[33] = "Robin of Locksley (Robin Hood)";
            studentNames[34] = "King Richard The Lionhearted";
            studentNames[35] = "Harry Potter";
            studentNames[36] = "John Smith";
            studentNames[37] = "King John";
            studentNames[38] = "William The Conqueror";
            studentNames[39] = "Bloody Mary";
            studentNames[40] = "Johnny Cash";
            studentNames[41] = "Sargon of Akkad";
            studentNames[42] = "Prince Absalom";
            studentNames[43] = "Eustace Clarence";
            studentNames[44] = "Ronald Weasley";
            studentNames[45] = "Rosa Parks";
            studentNames[46] = "Sandra Day O'Connor";
            studentNames[47] = "Queen Lucy Pevensie";
            studentNames[48] = "John The Apostle";
            studentNames[49] = "Kevin McAlister";
            studentNames[50] = "Alex Pruitt";
            studentNames[51] = "Guy Fawkes";
            studentNames[52] = "Queen Heshepshut";
            studentNames[53] = "King Ramases";
            studentNames[54] = "King Xerxes of Persia";
            studentNames[55] = "Nathan Hale";
            studentNames[56] = "Patrick Henry";
            studentNames[57] = "Jacob Marley";
            studentNames[58] = "Ebenezer Scrooge";
            studentNames[59] = "Saint Augustine";
            studentNames[60] = "John Lennon";
            studentNames[61] = "Forrest Gump";
            studentNames[62] = "Jenny Gump";
            studentNames[63] = "Luitenant Dan";
            studentNames[64] = "John Q. Public";
            studentNames[65] = "Bill Gates";
            studentNames[66] = "Harriet Tubman";
            studentNames[67] = "Sojourner Truth";
            studentNames[68] = "Malcom Little(Malcom X)";
            studentNames[69] = "Leonardo D. Caprio";
            studentNames[70] = "Jack Philps";
            studentNames[71] = "Paul Revere";
            studentNames[72] = "Becky Thatcher";
            studentNames[73] = "Tom Sawyer";
            studentNames[74] = "Samual Clemmons(Mark Twain)";
            studentNames[75] = "George Washington Carver";
            studentNames[76] = "Paul Bunyan";
            studentNames[77] = "Huck Finn";
            studentNames[78] = "Picos Bill";
            studentNames[79] = "Mark Anthony";
            studentNames[80] = "Queen Cleopatra";
            studentNames[81] = "Anne Frank";
            studentNames[82] = "Eli Wesel";
            studentNames[83] = "Eddie Brock";
            studentNames[84] = "Thorin Oakenshield";
            studentNames[85] = "Bilbo Bagins";
            studentNames[86] = "Frodo Baggins";
            studentNames[87] = "Sam Gamagee";
            studentNames[88] = "Gandalf the Gray";
            studentNames[89] = "Sauraman the Wise";
            studentNames[90] = "King George III";
            studentNames[91] = "William Wilberforce";
            studentNames[92] = "Merry Brandybuck";
            studentNames[93] = "Martin Luther King Jr.";
            studentNames[94] = "Jackie Robinson";
            studentNames[95] = "Sherwim Williams";
            studentNames[96] = "John Menard";
            studentNames[97] = "Chrisopher Columbus";
            studentNames[98] = "Genghis Khan";
            studentNames[99] = "Atilla The Hun";
            studentNames[100] = "Al Capone";
            studentNames[101] = "Napolean Bonepart";
            studentNames[102] = "Marie Antionette";
            studentNames[103] = "King Louis XVII";
            studentNames[104] = "Napolean Blownapart";
            studentNames[105] = "Yesser Arafat";
            studentNames[106] = "Al Gore";
            studentNames[107] = "Benedict Arnold";
            studentNames[108] = "Tim Allen";
            studentNames[109] = "George W. Bush";
            for (int x = 110; x < 500; x++)
            {
                studentNames[x] = "Student " + x;
            }
     
            for (int y = 0; y < 500; y++)
            {
                students[y] = new Student(studentNames[y]);
     
            }
     
            classNames = new String[35];
     
            classNames[0] = "Sleeping 101";
            classNames[1] = "Partying 202";
            classNames[2] = "Discrete Math";
            classNames[3] = "Rocket Science";
            classNames[4] = "Introduction to Data Structures";
            classNames[5] = "Skipping 303";
            classNames[6] = "Creative Writing";
            classNames[7] = "Introduction to Technical Communication";
            classNames[8] = "Easy Class";
            classNames[9] = "Surviving College";
            classNames[10] = "How To Outsmart the Profs";
            classNames[11] = "Astronomy";
            classNames[12] = "Thermodynamics";
            classNames[13] = "Long-winded Lectures 404";
            classNames[14] = "System Design";
            classNames[15] = "Physics";
            classNames[16] = "Chemistry";
            classNames[17] = "Tutoring";
            classNames[18] = "Politics 204";
            classNames[19] = "Very Hard Class";
            classNames[20] = "Introduction to Java Programming";
            classNames[21] = "Biology";
            classNames[22] = "Physical Education";
            classNames[23] = "Databases";
            classNames[24] = "World History";
            classNames[25] = "Philosophy";
            classNames[26] = "Daydreaming 404";
            classNames[27] = "Eating 208";
            classNames[28] = "Kung Fu Fighting";
            classNames[29] = "Religion";
            classNames[30] = "Film Making";
            classNames[31] = "How to Understand Women(Sorta) 467";
            classNames[32] = "How to Understand Men(Sorta) 468";
            classNames[33] = "TV Studio 303";
            classNames[34] = "Architecture";
     
            for (int z = 0; z < 35; z++)
            {
                classes[z] = new Class(classNames[z]);
     
            }
           System.out.println(classes[0].getName());
     
            Random rand = new Random();
            Set<Student> mix = new HashSet<Student>();
            Student[] st = new Student[classes[0].getSize()];
            for ( int i = 0; i < classes[0].getSize(); i++ ){
                int rN = rand.nextInt(classes[0].getSize());
                while ( mix.contains(students[rN]) ){//already chose
                    rN = rand.nextInt(classes[0].getSize());//get another
                }
                mix.add(students[rN]);
               mix.toArray(st);
     
              st = mix.toArray(st);
            }
     
     
     
            for (int k = 0; k < classes[0].getSize()  ; k++)
            {
                classes[0].addStudents(st[k]);
            }
     
            // System.out.println(classes[0].getName());
            // System.out.println(students[0].getName());
            System.out.println(classes[0].toString());
            outFile.println(classes[0].toString());
            outFile.close();
     
            Random rand2 = new Random();
            Set<Student> mix2 = new HashSet<Student>();
            Student[] st2 = new Student[classes[1].getSize()];
            for ( int i2 = 0; i2 < classes[1].getSize(); i2++ ){
                int rN2 = rand.nextInt(classes[1].getSize());
                while ( mix2.contains(students[rN2]) ){//already chose
                    rN2 = rand.nextInt(classes[1].getSize());//get another
                }
                mix2.add(students[rN2]);
               mix2.toArray(st2);
     
              st2 = mix2.toArray(st2);
            }
     
            for (int k2 = 0; k2 < classes[1].getSize()  ; k2++)
            {
                classes[1].addStudents(st2[k2]);
            }
     
            // System.out.println(classes[0].getName());
            // System.out.println(students[0].getName());
            System.out.println(classes[1].toString());
        }
     
        public static void main(String[] args) throws FileNotFoundException
        {
            MainClass mainC = new MainClass();
        }
    }

    package DiscreteMathProject;
     
    /**
     * @author pradcoc
     *
     */
    public class Student {
     
        private String name;
        private int numOfClasses;
        private ArrayList<Class> aList;
        private ArrayList<String> aList2;
     
        public Student(String name)
        {
     
            name = this.name;
             setName(name);
        }
     
        public String getName()
        {
            return name;
        }
     
        public void setName(String name2)
        {
        	name = name2;
        }
     
       public void addClasses(Class c)
    {
    aList.add(c);
    }
     
    public String getClasses()
    {
    for (int i = 0; i < aList.size(); i++)
            {
                aList2.add(aList.get(i).getName());
            }
     
            String str = aList2.toString();
            return str;
     
    }
     
    public int getNumOfClasses()
    {
    numOfClasses = aList2.size();
    return numOfClasses;
    }
     
    public String toString()
    {
    String str = "The student's name is: " + getName() + ".  The student is in " + getNumOfClasses() + " classes.  The classes are " + getClasses() + ".";
    return str;
    }
     
    }

    package DiscreteMathProject;
     
    import java.util.ArrayList;
    import java.util.Random;
     
    /**
     * @author pradcoc
     *
     */
    public class Class {
     
        private Student[] students;
        private String[] times;
        private String name;
        private String time;
        private int size;
        private Random r,r2;
        private Random[] random;
        private ArrayList<Student> aList;
        private ArrayList<String> aList2;
     
        public Class(String name)
        {
     
            name = this.name;
            times = new String[10];
            times[0] = "8:00 a.m.";
            times[1] = "9:30 a.m.";
            times[2] = "11:00 a.m.";
            times[3] = "12:30 p.m.";
            times[4] = "2:00 p.m.";
            times[5] = "3:30 p.m.";
            times[6] = "5:00 p.m.";
            times[7] = "6:30 p.m.";
            times[8] = "8:00 p.m.";
            times[9] = "9:30 p.m.";
            aList = new ArrayList<Student>();
       aList2 = new ArrayList<String>();
          setName(name);
     
     
        }
        public String getTime()
        {
            r = new Random();
            int x = r.nextInt(10);
            time= times[x];
            return time;
        }
     
        public String getName()
        {
            return name;
        }
     
        public void setName(String name2)
        {
        	name = name2;
        }
     
        public void addStudents(Student s)
        {
     
            aList.add(s);
     
        }
     
    public String  getAdjacentClasses(Class[] classes)
    {
    ArrayList<String> penguinList = new ArrayList<String>();
     
    for (int i = 0; i < classes.length; i++)
    {
     
    // how do I get it so that it checks the getArrayList2() method of each class and checks to see if 
    // the get method, for any index, returns true, i.e., they have a Student in common
    // I'm baffled how to do it without it throwing some exception somewhere or making a glitch somewhere
     
    }
     
    }
     
        public ArrayList<Student> getArrayList()
        {
            return aList;
        }
     
        public int getSize()
        {
        r2 = new Random();
     
        int x = r2.nextInt(26);
        if (x < 15)
        {
            x = 15;
            size = x;
            return size;
        }
     
     
        else
        {
        size = x;
        return size;
        }
        }
     
        public String toString()
        {
            String str = "The class: " + getName() + " is at " + getTime() + "and has " + getSize() + " students." +
            " The students in it are: " + getStudentsInClass() + "." ;
            return str;
        }
     
        public String getStudentsInClass()
        {
     
            for (int i = 0; i < getSize(); i++)
            {
                aList2.add(aList.get(i).getName());
            }
     
            String str = aList2.toString();
            return str;
        }
     
    public ArrayList<String> getStudentsInClass2()
    {
    return aList2;
    }
    }

    I need help with method getAdjacentClasses(Class[] classes) and also am still wondering why my arrayList Size won't always be in bounds.

    Thanks.
    Last edited by javapenguin; November 9th, 2010 at 03:12 PM. Reason: Hoping that someone will please respond.

  20. #17
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

    What's this used for:

     


    What goes in here?


    Last edited by javapenguin; November 10th, 2010 at 02:32 PM.

  21. #18
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

    Let's see:

     

    Sleeping 101
    The class: Sleeping 101 is at 6:30 p.m.and has 15 students. The students in it are: [Abraham Lincoln, Joe McDonald, Thomas Edison, Luke Skywalker, Sherlock Holmes, Susan B. Anthony, Albert Einstein, Julius Ceasar, George Herman (Babe) Ruth, John Wayne, Martin Luther, Fidel Castro, James Bond, Adolf Hitler, Paul Adcock, Darth Vader].
     
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 15, Size: 15
    at java.util.ArrayList.RangeCheck(ArrayList.java:547)
    at java.util.ArrayList.get(ArrayList.java:322)
    at Class.getStudentsInClass(Class.java:121)
    at Class.toString(Class.java:112)
    at MainClass.<init>(MainClass.java:240)
    at MainClass.main(MainClass.java:245)





  22. #19
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

    classes[1].addStudents(st2[k2]);

    What's wrong with this code?

  23. #20
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Using Random class

    I won't even try to answer that. Change the name of your class called Class. In general, avoid reusing names of classes that already exist in the standard JDK, and more specifically, don't ever use a class name that could clash with the classes in the java.lang package.

    db

  24. The Following User Says Thank You to Darryl.Burke For This Useful Post:

    javapenguin (November 11th, 2010)

  25. #21
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

    No, the problem is my ArrayList of students in a class.

    Also, the java class Class has a <T> . Mine has no, what're they called? (Parameters in < >)

    Maybe data parameters is the word I'm looking for.

    My class Class has a public constructor.

    The compiler can, sorta, call methods from my class Class, though why the constructor isn't itself calling the setName(), even though I called it in the constructor, is beyond me.

    I'm convinced it's the method that sets the class size or the method that adds students to a class. It's sometimes adding their names, but not them, or something.

  26. #22
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

    It's something wrong with my ArrayList.

    Also, how do I get it to check each class to see if any other classes have students in common?

    Once done with that, I'd like to make a TreeMap.

    It'll have a Class and a list of the names of other classes that have a student in common with that class.

  27. #23
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Using Random class

    Ok, maybe not a TreeMap.

Similar Threads

  1. Generation of random number using random class
    By JavaPF in forum Java SE API Tutorials
    Replies: 1
    Last Post: December 7th, 2011, 05:46 PM
  2. random
    By b109 in forum Java Theory & Questions
    Replies: 2
    Last Post: June 3rd, 2010, 04:19 AM
  3. Random Access File
    By silver_unicorn in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: August 10th, 2009, 10:44 PM
  4. Random numbers
    By Pooja Deshpande in forum Java SE APIs
    Replies: 8
    Last Post: June 5th, 2009, 04:36 AM
  5. [SOLVED] Random number method implementation
    By big_c in forum Java Theory & Questions
    Replies: 2
    Last Post: April 15th, 2009, 01:10 PM