Grouping Students From ArrayList
Jan 12, 2015
I have an ArrayList filled with Student objects and all these students have a name. What I have to do is group these students in teams of 2 and make sure that 1. a student is not grouped with itself and 2. a student is not grouped twice.
The problem shows up when I iterate through the ArrayList and crosscheck a randomly generated number (for picking random students) with an ArrayList that contains already selected students, to make sure that we have no duplicates.
Here is my code:
public void generateTeams() {
Iterator<Student> iteration = studentsArray.iterator();
while(iteration.hasNext()) {
student1 = iteration.next();
// getRandomStudent returns a random Student object from the arraylist
student2 = getRandomStudent();
[Code] .....
If I run it like this the program will freeze an take up a lot of CPU. This is probably because the final student has no other students left to pair with and will therefore keep randomly generating a number (the while loop in the middle). The list of students is 27 long so it has to work with an odd amount of students.
Any good way to crosscheck if the student has been picked before? I have tried emptying the original ArrayList before but that ends up with the same problem of there being no students to match with.
In the while loop I have edited out the part that causes it to generate random numbers infinitely. I do need to make sure the student hasn't been picked before though.
View Replies
ADVERTISEMENT
Nov 27, 2014
I need to write a program that checks whether a Java source-code file has correct pairs of grouping symbols and the program must implement the Stack<E> class to solve this problem.
Here is the file:
[a({b,c}x{d,e})%x]
(1+(2-3)/4+[(a-({b+c}*5)/2)+e]
(a{b(c]}a)
I tried something like this, but I'm not exactly sure what I am doing wrong:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Stack;
public class Driver {
[Code] .....
View Replies
View Related
Apr 4, 2015
A school has 100lockers and100 students. All lockers are closed on the first day of school. As the students enter, the first student, denoted S1, opens every locker. Then the second student, S2, begins with the second locker, denotedL2, and closes every other locker. Student S3beginswiththethirdlocker and changes every third locker (closes it if it was open, and opens it if it was closed). Student S4begins with locker L4 and changes every fourth locker. StudentS5 starts with L5andchanges every fifth locker, and soon,until student S100 changesL100.
After all the students have passed through the building and changed the lockers, which lockers are open?Write a program to find your answer. The program should display the answer like this:
Locker x is open Locker y is open...
Locker z is open
Design requirement:
Use a method and an array of100 boolean elements,each of which indicates
whether a locker is open (true) or closed (false). Initially,all lockers are closed.
I'm not sure why it's giving me errors in my code. I'll post it below.
1
2 public class Assignment5 {
3
4 public static void main(String[] args) {
5 //create array
6boolean locker[] = new boolean[100];
7 //make them all closed
8for( int i = 0; i <= 99; i++){
9locker[i]= false;
[Code] ....
I have errors in line 12 and 14 but not sure why or how to fix them.
View Replies
View Related
Jun 18, 2014
I have the program bellow that grades students(based on a two dimensional array with the answers) and i need to make it display the students based on the grades/scores in ascending order . I did that in two ways (using a array and a two dimensional array) but i have a hunch it can be done much more simple then i did it (but still using array object and nothing else ) .
public class GradeExam {
/** Main method */
public static void main(String args[]) {
// Students' answers to the questions
char[][] answers = {
[code]....
My first solution creating an array with the grades for sorting :
public class C8_3 {
public static void main(String args[]) {
// Students' answers to the questions
char[][] answers = {
{'A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
{'D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'},
[code]....
View Replies
View Related
Apr 14, 2014
The purpose of this project is to determine the letter grade of students. The program needs to accept two command line arguments:
The first being the name of a disk file that contains the names of students, and their test scores, separated by commas followed by one or more spaces. Each line in the file will contain scores for one student.
The second argument is the name of an output disk file. The program is supposed to create a new output disk file using that name.
The number of students in the input file is unknown during compile time. The name of input and output files could be anything and only known during run time. Additionally, the average scores, along with the minimum and maximum scores for each test are to be displayed in the console.
Calculation: Final Score = quiz1 * .10 + quiz2 * .10 + quiz3 * .10 + quiz4 * .10 + midi * .20 + midii * .15 + final * .25
Final Score >= 90% then letter grade is A, 80%-89% B, 70%-79% C, 60-69% D, <= 59% F
input_data.txt:
firstName lastName, 100, 90, 80, 100, 89, 99, 88
firstName lastName, 90, 90, 100, 100, 99, 100, 95
firstName lastName, 100, 90, 100, 70, 78, 78, 80
firstName lastName, 80, 90, 90, 100, 89, 99, 85
etc.
output_data.txt
firstName lastName: B
firstName lastName: A
firstName lastName: F
firstName lastName: B
firstName lastName: C
averages (to appear in console)
Q1 Q2 Q3 Q4 MidI MidII Final
Average: 82.25 80.38 82.85 83.88 81.38 84.13 78.63
Minimum: 60 54 38 62 62 60 50
Maximum: 100 90 100 100 99 100 95
Press ENTER to continue...
Here's what I have so far :
import static java.lang.System.out;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
public class LetterGrader {
[Code] .....
View Replies
View Related
Dec 13, 2014
Here is the question with my Pseudocode:
Create an application that keeps track of students. The application should have 3 new classes.
1. Create a class which will represent an instance of 1 student:
I want to be able to display the user's name (Last, First), Age (in years as an integer) and GPA (to 2 decimal points). This class only needs a constructor and a toString method.
2. Create a Team class that will represent a group of students.
This class should allow the driver class to manage students for a given course. The class will keep track of the course name and section, the students in the class, and allow the driver to specify the max number of students to keep track of.
Methods:
1.Constructor
2.It should have a method to insert a single student into the array and return a Boolean indicating success or failure.
3.It should also have a method which returns a string with all of the course and student information formatted for display. You should make the name 12 characters long.
3. Create a driver class that will manage the whole process.
Pseudocode:
BEGIN Driver main method
Initialize student count to 0
Input size of the array
Instantiate a copy of the Team class
Input a student name (or quit)
WHILE (the student name is not quit)
Input student age
Input student GPA
[Code] ....
View Replies
View Related
Apr 16, 2014
I am making a gradebook program that calculates the averages of 25 students using 2D arrays in which the students have four test grades. I have figured out how to display the averages of each student in one column but I cant seem to figure out how to display the letter grade of the average into another column.
Right now my program reads from a .txt doc
Heres what I've got.
TestGradeBook.java
import java.util.*;
import java.io.*;
public class TestGradeBook {
public static void main (String [] args ) throws IOException{
//Declarations
final int ROWS = 100;
final int TESTS = 4;
[Code] .....
GradeBook_Data.txt
Name100100100100
// basic name and grades
View Replies
View Related
Aug 27, 2014
I want to develop a dynamic scheduling application that I hope to use at work, but I have some questions about the design approach since this is my first undertaking of this kind of project.
The purpose of the application is to display a chart showing the lesson times for a particular teacher and her students.
Here's are more important details:
-The chart displays the current day's schedule.
-The top row displays the teacher's name. There are at least 4 teachers each day.
-The leftmost column shows the times (from 3:00 to 8:00).
-The table is filled with the names of the students.
My current problem is deciding on the best approach to storing this data containing the teacher and her students and times. I should also note that there are about 500 students and around 20 teachers (i.e. the dataset is small). Is this a problem solved using a database and JDBC or could I just write the data to file? Are there other approaches that would solve this problem?
View Replies
View Related
Feb 28, 2014
I'm trying to create my own arraylist using Collection. My program doesn't do anything. Obviously, I haven't a clue.
import java.util.Collection;
import java.util.Iterator;
public class MyArrayList<T> implements java.util.Collection<T> {
private int size = 4;
private T[] mArray;
public MyArrayList(String[] args) {
[Code] ....
View Replies
View Related
Jul 8, 2014
I have stumbled onto a problem with ArrayLists (not sure if nested ArrayList objects would be a more accurate description) ....
As simply put as I can describe it, I have an Inventory class which creates an ArrayList of a Product superclass, which has two subclasses, PerishableProduct and ItemisedProduct.
By default, the program is meant to have a starting inventory, which is why I have added them in the constructor
public class Inventory {
private List<Product> products;
public Inventory() {
addProduct(new Product("Frying pan", 15, 20));
addProduct(new PerishableProduct("Apple", 5.8, 30, 7));
addProduct(new ItemisedProduct("Cereal", 5.8, 0));
// this is where I am having problems. Wanting to add
// objects to the ItemisedProduct's ArrayList for cereal.
}
Within the ItemisedProduct subclass is yet another ArrayList which is meant to hold serial numbers.
public class ItemisedProduct extends Product {
private ArrayList<String> serialNumbers = new ArrayList();
public ItemisedProduct(String name, double price, int qty) {
super(name, price, qty)
[Code] .....
My problem is that I do not know how to populate the serialNumbers ArrayList from the Inventory class' constructor. Because technically, quantity is defined by how many serial numbers are created.
View Replies
View Related
Feb 26, 2015
I think it's a problem with my if then else statements but I'm not sure?
package Hw1;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class ScrapWork {
public static void main(String[] args){
String[]Dalton={"Joe","William","Jack","Averell"};
[Code] .....
run:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - illegal start of type
at Hw1.ScrapWork.main(ScrapWork.java:16)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
View Replies
View Related
Nov 14, 2014
I have an ArrayList with String, String, Double.
From another class I would like to print minimum and maximum including the first String name.
I have tried with import java.util.Collections; but that didn't work.
Java Code:
ArrayList<List>list = new ArrayList<List>();
list.add(new List("Abc","Cba",1));
list.add(new List("Bca","Bca",5));
list.add(new List("Cba","AcB",2)); mh_sh_highlight_all('java');
I would like the result to look like:
Minimum: Abc 1
Maximum: Bca 5
View Replies
View Related
Jun 2, 2014
Something like ArrayList<Object>[] = new ArrayList<Object>[]();
View Replies
View Related
Feb 14, 2015
I have an ArrayList of employee and ArrayLsit of bosses, and I want to keep those people in a temporary ArrayList , then ordain alphabetically by name, to sort I use the interface comparator.
The problem comes when I will order 2 ArrayList(workers and bosses), because every time I call I use these functions or not is ordered (sortByNameAlphabetical())
public class Employee {
private String name;
public String getName() {
return name;
}
@Override
public String toString() {
return name ;
[Code]...
View Replies
View Related
Apr 7, 2015
I'm creating a card game assignment... so i have an arraylist called cards that has 20 cards and every card has contains 2 objects, suit and the point Value.
I shuffled the deck, now i want to add half of it to player 1 and the rest of the cards goes to the bot or computer.
how can i add the cards to the player one arraylist and have all the information of the cards?
here is my Deck class code :-
public class Deck {
private ArrayList cards;
private int size;
private ArrayList player1;
private ArrayList bot;
[code]....
the problem i have is this one doesn't work
size = cards.size() / 2;
for (int i = 0; i < size - 1; i++) {
player1.add(cards.get(i));
}
for (int s = size; s < cards.size() - 1; s++) {
bot.add(cards.get(s));
}
View Replies
View Related
Sep 18, 2014
Right now, i'm trying to do is when a user clicks on my GUI button, it would display a text of information on the button they selected. I'm using an arraylist of objects and i'm trying to input the function inside the mouse click function. But I'm not sure how to properly display that information. Here is my GUI code. I'm working on the raven button. I have animal interface, with a parent class of Bird, and child class of Raven. How I could display this correctly...
public class AnimalJF extends JFrame {
private JPanel contentPane;
private JTextArea textArea = new JTextArea();
/**
* Launch the application.
*/
public static ArrayList<Bird> Birdlist = new ArrayList<Bird>();
public static void main(String[] args) {
Birdlist.add(new Eagle());
[Code] .....
View Replies
View Related
Nov 21, 2014
I am currently working on a program that will read from a .txt file to create an arraylist. I will be working with the objects in the list to perform computations and display the data. The .txt file is in the following format: lastName firstName hoursWorked hourlyRate
With no delimiters. I've messed with this thing way too much in the last 12 hours (only day off for the week ) so variable names etc have changed often. At present the error I am receiving is "error: constructor GrossPayService in class GrossPayService cannot be applied to given types".
import java.util.*;
import java.io.*;
import java.text.*;
class AryListObjects
{
public static void addEmployee(String firstName, String lastName, double hoursWorked, double hourlyRate)
{
ArrayList<GrossPayService> employees = new ArrayList<GrossPayService>();
[code]....
View Replies
View Related
Dec 7, 2014
I've this "program" that shall manage to register a dog, show a list of all registerd dogs and delete dogs from the list.. And I'm stuck at the latter one. So I've to classes, one for the dog and one for register/program. This is my main program
package hundRegister;
import java.util.Scanner;
import java.util.ArrayList;
public class HundProgram {
private static Scanner tangentbord = new Scanner (System.in);
private static ArrayList<Hund> hundlista = new ArrayList<>();
[Code] ......
So, when I enter a name on a dog that exist on my list, it just jumps down to } else { and write that dog can't be found even if I write the exact name on the dog.
I can't see what I'm doing wrong, been trying out different methods now.
View Replies
View Related
Apr 3, 2014
I'm making a program for my class's chapter on classes. I need to make a program that makes a grocery list using an array. Here's the assignment from the book.
Write a class named GroceryList that represents a list of items to buy from the market, and another class named
GroceryItemOrder that represents a request to purchase a particular item in a given quantity (example: four boxes
of cookies). The GroceryList class should use an array field to store the grocery items and to keep track of its size
(number of items in the list so far). Assume that a grocery list will have no more than 10 items. A GroceryList
object should have the following methods:
public GroceryList()
Constructs a new empty grocery list.
public void add(GroceryItemOrder item)
Adds the given item order to this list if the list has fewer than 10 items.
public double getTotalCost()
Returns the total sum cost of all grocery item orders in this list.
The GroceryItemOrder class should store an item quantity and a price per unit. A GroceryItemOrder object
should have the following methods:
public GroceryItemOrder(String name, int quantity, double pricePerUnit)
Constructs an item order to purchase the item with the given name, in the given quantity, which costs the given price
per unit.
public double getCost()
Returns the total cost of this item in its given quantity. For example, four boxes of cookies that cost 2.30 per unit
have a total cost of 9.20.
public void setQuantity(int quantity)
Sets this grocery item’s quantity to be the given value.
I have the assignment mostly done, but the JUnit test case our teacher gave us to test it tests add() an array instead of an array list. For this reason, I need to change my program to use an array. My code is below.
import java.util.*;
public class GroceryList {
private ArrayList<GroceryItemOrder> list;
int num;
public GroceryList() {
list = new ArrayList<GroceryItemOrder>(10);
[Code] .....
View Replies
View Related
Jun 30, 2014
How can i sort my ArrayList, which contains cars, with year and used year, i want to sort them first from year, and then from used year . what should i use?
View Replies
View Related
Nov 12, 2014
I am trying to add the contents of the iterator to an arraylist so I can do other stuff to it, however I am getting an error when I actually try adding it to the list, stating that
"The method add(Map.Entry<String,myObject>) in the type ArrayList<Map.Entry<String,myObject>> is not applicable for the arguments (myObject)"
Here is what I have tried doing:
Iterator<Map.Entry<String, myObject>> iterator = hash.entrySet().iterator();//hash is my HashMap object
ArrayList<Map.Entry<String, myObject>> list = new ArrayList<Map.Entry<String, myObject>>();
while(iterator.hasNext()){
Map.Entry<String, myObject> entry = iterator.next();
list.add(entry.getValue());//error here
}
View Replies
View Related
Mar 1, 2014
I am trying to read a file into an array list, change some things about it, and then write it to another file. Files are getting written with what was read repeating a second time. I've tested the read method by having it print everything which goes into the ArrayList object. I then did the same with the write method which seems to write everything twice, as if everything is in the ArrayList twice, but I'm not sure how this is possible, since the read clearly did everything only once. Perhaps the ArrayList isn't the best collection to use for this purpose.
The read method:
Java Code:
private ArrayList<String> read(File in) {
String line;
ArrayList<String> data = new ArrayList<String>();
try {
BufferedReader r = new BufferedReader(new FileReader(in));
[code]....
View Replies
View Related
Nov 26, 2014
I have to sort out my ArrayList but cannot make it work. Here is
Java Code:
Collections.sort(this.users);
User poor = this.users.get(0);
User ritch = this.users.get((this.users.size()-1));
System.out.println("Poorest user has" + poor.getUsername() + poor.getBalance() );
System.out.println("Ritches user has " + ritch.getUsername() + poor.getBalance() + "
"); mh_sh_highlight_all('java');
The Collections.sort(this.users); does not work.
View Replies
View Related
Mar 15, 2015
I have a ArrayList of objects of class called HockeyPlayer (ArrayList<HockeyPlayer>). A HockeyPlayer has a String name and int number of goals.
This is my current work for comparing each object in the list to every other and printing them to screen:
Iterator<HockeyPlayer> it = hockeyPlayersList.iterator();
while (it.hasNext()) {
HockeyPlayer singleHockeyPlayer = it.next(); //the first one encountered
// HockeyPlayer nextHockeyPlayer = it.next(); //the next one encountered
[Code]...
This of course produces some duplication in the print-out: These are the equal hockey players: Who Ever wears jersey. This type of employee is paid: true. This employee has post-secondary education: false. This employee's work is to play. This hockey player has scored 0 goals.
Jason Harrison wears jersey. This type of employee is paid: true. This employee has post-secondary education: false. This employee's work is to play. This hockey player has scored 0 goals.
These are the equal hockey players: Jason Harrison wears jersey. This type of employee is paid: true. This employee has post-secondary education: false. This employee's work is to play. This hockey player has scored 0 goals.
Who Ever wears jersey. This type of employee is paid: true. This employee has post-secondary education: false. This employee's work is to play. This hockey player has scored 0 goals.
How do I remove the duplication in the print-out?
View Replies
View Related
Jul 7, 2014
I am new on java. I have following xml file structure. What I need to do is that :
1) Read this xml file and convert to arraylist.
2) insert this arrayList into Mysql database.
XML File is
<?xml version="1.0"?>
<root>
<individualorders>
<individualorder>
<patientRole>
<id>8839</id>
[Code] ....
View Replies
View Related
Feb 11, 2014
I am trying to access an array of "Movie" objects in my jsp. The array is loaded via
org.springframework.web.servlet.ModelAndView.addObject().
Here is my jsp code:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
[Code] .....
The System.out.println("jsp page: .... &> results in the output: "jsp page: movielist - [Title: Die Hard; Budget: 20000000, Title: two days in paris; Budget: 1000000]" so I am confident the objects are being loaded into the ModelAndView correctly. However the output of the block is "${movie.name}" instead of the list of movies. My movie object has a getName() method to return a string (and a setName() method). I am not sure why the System.out.println statement can find the movielist attribute, but ${movie.name} is being treated a plain text. There are no execptions thrown or other indications of errors.
View Replies
View Related