so i'm trying to pass an initialized object which is "p" from one file to method add() in another file. Null exception occurs at storage[count]=p
public class PlayerList {
private static final int INITIAL_SIZE = 2;
private Player[] storage;
private int count;
public PlayerList() {
// Initialize the storage array and set count to 0.
Player[] storage = new Player[2];
storage[0] = new Player("default name1");
storage[1] = new Player("default name2");
count = 0;
}
public void add(Player p) {
storage[count] = p;
count++;
}
//In another file:
public static void PlayerListTestOne() {
System.out.println("PlayerList testing: constructor, size, add, get(0), find");
PlayerList l = new PlayerList();
Player p = new Player("Derek Jeter");
displayResults(l.size() == 0);
l.add(p);
displayResults(l.size() == 1);
displayResults(l.get(0).equals(p));
displayResults(l.find(p) != -1);
}
Related
The goal of my program is to store data for students(First Name, Last Name, ID#).I'm trying to create 4 Arrays. One array will hold the combined value of each student object that I'm adding(myDB). The other 3 hold indexes to the original spot of each value(Fname,Lname,ID) and add them to an ordered array without sorting the array. The trouble I'm having is that once I add something to the Index Arrays and go to print them, it prints all of the IDs regardless of what object I call.
//class containing methods to list, add, and delete
//Class that declares the main database array that holds all three (ID,First,Last)
import java.io.FileInputStream;
import java.util.*;
public class DataBase
{
private String tempID, tempFname, tempLname;
private DataBaseArray myDB;
private int nextDBRecord;
private IndexArray ID;
private IndexArray First;
private IndexArray Last;
public DataBase()
{
nextDBRecord = 0;
myDB =new DataBaseArray(100);
ID=(new IndexArray(100));
First=new IndexArray(100);
Last=new IndexArray(100);
}
void addData(String last, String first, String id)
{
tempLname = new String(last);
tempFname = new String(first);
tempID = new String(id);
//ID.insert(new IndexRecord(tempID, nextDBRecord));
First.insert(new IndexRecord(tempFname,nextDBRecord));
Last.insert(new IndexRecord(tempLname,nextDBRecord));
//Adds to main DB with
myDB.getStudentArray()[nextDBRecord]= (new DataBaseRecord(tempLname,tempFname,tempID));
System.out.println(myDB.getStudentArray()[nextDBRecord]);
nextDBRecord++;
}
void addIt ()
{
Scanner keyb = new Scanner(System.in);
System.out.println("Please enter the ID for new student entry");
tempID=keyb.next();
ID.insert(new IndexRecord(tempID, nextDBRecord));
System.out.println("Please enter the first name of the new student");
tempFname=keyb.next();
First.insert(new IndexRecord(tempFname, nextDBRecord));
System.out.println("Please eneter the last name of the new student");
tempLname=keyb.next();
Last.insert(new IndexRecord(tempLname,nextDBRecord));
//Adds to main DB with
myDB.getStudentArray()[nextDBRecord]= (new DataBaseRecord(tempLname,tempFname,tempID));;
nextDBRecord++;
}
void findIt()
{
}
void list (int type, int order)
{
First.printIt(order);
}
}
//Class that creates the objects to add to Iarray Farray Iarray
//IndexArray is a static array
//Creates a single entry into the IndexArray
//Need a compareTo method that gives the where value of each object
public class IndexRecord
{
private String key; //Value
private int where; //Where it is at in DataBaseArray
IndexRecord (String value, int position)
{
setKey(new String(value));
where = position;
}
public String toString()
{
return getKey()+" "+ String.valueOf(where);
}
public String getKey() //Getter for key value of the new student that is being added
{
return key;
}
public void setKey(String key) //Setter for key value of the new student that is being added
{
this.key = key;
}
}
//Same as OrderedArray Class
//Add Iterator methods. Instead of printing here, tell DataBase class what DatabaseRecord objects to print
public class IndexArray
{
private static IndexRecord[] irArray;
private int nOfElem; //Should be the same for each array so only 1 counter is needed
private int maxSize;
private int theIterator;
public IndexArray(int size)
{
nOfElem = 0;
maxSize=size;
irArray = new IndexRecord[size];
}
//-----------------------------Getters and Setters-------------------------------------
public int size() //Getter to find num of elements in array that can be called in other class
{ return nOfElem; }
public IndexRecord[] getIRarray()
{
return irArray;
}
//---------------------Iterator Methods-----------------------------------------------------
void iteratorToFront()
{
theIterator=(nOfElem>0? 0 : -1);
}
void iteratorToBack()
{
theIterator=(nOfElem>0 ? nOfElem-1 : -1);
}
boolean hasNext()
{
return (theIterator==nOfElem-1? false:true );
}
boolean hasPrevious()
{
return (theIterator==0? false : true);
}
public IndexRecord getIterator()
{
return(theIterator==-1 ? null :irArray[theIterator]);
}
int getNext()
{
theIterator=(hasNext()? theIterator+1: -1);
return(theIterator==-1? null : theIterator);
}
int getPrevious()
{
theIterator=(hasPrevious()? theIterator-1:-1);
return (theIterator==-1? null : theIterator);
}
//------------------Methods Called In Main---------------------------------------
public boolean insert(IndexRecord ir)
{
if(maxSize==nOfElem) return false;
int j;
for(j=nOfElem-1;j>=0;j--)
{
if(irArray[j].getKey().compareToIgnoreCase(ir.getKey())<0)break;
{
irArray[j+1]=irArray[j]; //Pushes all objects down to make room for new one
}
}
irArray[j+1]=ir;
nOfElem++;
return true;
}
public int find(String searchKey)
{
int lowerBound = 0;
int upperBound = nOfElem-1;
int currentRef;
while(true)
{
currentRef = (lowerBound + upperBound) / 2;
String tempValue = String.valueOf(irArray[currentRef].getKey());
if(tempValue.compareTo(searchKey) == 0)
return currentRef;
else if (lowerBound > upperBound)
return nOfElem; //returns a pointer to an empty slot
else
{
if(tempValue.compareTo(searchKey) > 0)
lowerBound = currentRef++;
else
upperBound = currentRef - 1;
}
}
}
//delete
public void printIt(int order)
{
switch(order)
{
case -1:
iteratorToBack();
break;
case 1:
iteratorToFront();
while(hasNext())
{
System.out.println(irArray[getNext()]);
}
break;
default:
}
}
}
I am trying to fill UCFCourse courseOne in my constructor with a courses[] object in fillWithCourses().UCFCourse courseOne does populate outside of the constructor but will not go into it.
public class UCFSemester<courses> {
private static UCFCourse courseOne;
private static double totalSemesters;
private static double completionTime;
static boolean fillSemester = true;
public UCFSemester(UCFCourse courseOne, UCFCourse[] coursetwo) {
this.courseOne = courseOne;
}
public static UCFCourse getcourseOne() {
return courseOne;
}
public static void setCoursesone(UCFCourse courses) {
courseOne = courses;
}
public static void fillWithCourses(UCFCourse courses[], int l) {
int x = 0;
while (fillSemester) {
for (int n = 0; n < 5; n++) {
if (x != n && courses[x].getCourseLevel() < courses[n].getCourseLevel()) {
setCoursesone(courses[x]);
}
}
fillSemester = false;
}
}
}
Side question.How can I access this all in a non-static way?I need the entire thing to be non-static but no matter what I do I can't get it.Thanks!
You can simply do it by creating a List like this:
public class UCFSemester {
private List<UCFCourse> courseList = new ArrayList<>();
public UCFCourse getCourse(int index) {
return courseList.get(index);
}
public void addCourses(UCFCourse[] courses) {
for(int x = 0; x < courses.length; x++) {
courseList.add(courses[x]);
}
}
}
Here, I'm assuming that you are passing the UCFCourse[] array with all the course details that are there in that particular semester.
addCourses() function will take this array and then add all the corresponding courses to the List.
getCourse() function will return you any particular course from the List (Using Index). You can also modify the search in any way you want.
This is my sticking point: I need to create an array of Chair objects with default woodType. I am able to declare the array itself, but obviously all the values are null. When I try to instantiate each Chair object in the array, I get errors. I'm not sure what I am doing wrong when trying to instantiate, please help.
public class PAssign3 {
public static void main(String[] args) {
TableSet set1 = new TableSet();
TableSet set2 = new TableSet(5, 7, 4);
// Chair chr1 = new Chair();//this works properly, setting wood as Oak
// Chair chr2 = new Chair("Pine");//works
}
}
class TableSet {
Table table = new Table();
private int numOfChairs = 2;
//creates an array that can hold "numOfChairs" references to same num of
//chair objects; does not instantiate chair objects!!!
Chair[] chairArr = new Chair[numOfChairs];
//instantiate each chair object for length of array
//this loop does not work; Error: illegal start of type
for (int i = 0; i < numOfChairs.length; i++) {
chairArr[i] = new Chair();
}
public TableSet() {
}
public TableSet(double width, double length, int numOfChairs) {
table = new Table(width, length);
this.numOfChairs = numOfChairs;
chairArr = new Chair[numOfChairs];
//this loop also does not work; Error: int cannot be dereferenced
for (int i = 0; i < numOfChairs.length; i++) {
chairArr[i] = new Chair();
}
}
public void setNumOfChairs(int numOfChairs) {
this.numOfChairs = numOfChairs;
}
public int getNumOfChairs() {
return numOfChairs;
}
public String getChairWoodType() {
return chairArr[0].getWoodType();
}
}
class Table {
private double width = 6;
private double length = 4;
public Table() {
}
public Table(double width, double length) {
this.width = width;
this.length = length;
}
public void setWidth(double width) {
this.width = (width < 0) ? 0 : width;
}
public void setLength(double length) {
this.length = (length < 0) ? 0 : width;
}
public double getWidth() {
return width;
}
public double getLength() {
return length;
}
}
class Chair {
private String woodType = "Oak";
public Chair() {
}
public Chair(String woodType) {
this.woodType = woodType;
}
public void setWoodType(String woodType) {
this.woodType = woodType;
}
public String getWoodType() {
return woodType;
}
}
int is a simple type in Java and does not have any methods or fields. Just omit this .length and the error is gone. It seems to me it already stores the actual number of chairs (2).
I want to operate on the array called "players" that is declared in the main method. I want to use "players" in my class called "Glucksspielthread"
I know that I can't access "players" because it is declared in the main method and is not visible for other classes.
How can I solve this problem? Here is my code:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Glucksspieltest {
public static void main(String[] args) {
int numPlayers = Integer.parseInt(args[0]);
int threadSize = Integer.parseInt(args[1]);
ExecutorService es = Executors.newFixedThreadPool(threadSize);
Glucksspielthread[] players = new Glucksspielthread[numPlayers];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Glucksspielthread(i);
es.execute(players[i]);
}
}
}
class Thinker {
public static void think(int Millisekunden) {
try {
Thread.sleep(Millisekunden);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void randomThink(int minMillisekunden, int maxMillisekunden) {
System.out.println("test");
}
}
class Glucksspielthread implements Runnable {
public int playerNumber;
Glucksspielthread(int number) {
playerNumber = number;
}
#Override
public void run() {
for (int i = 0; i <= playerNumber; i++) {
// here, I want to operate on array called "players" that is declared in the main method
}
}
}
Just for your test purpose make your players variable static and public in the Glucksspieltest class, like this:
public class Glucksspieltest {
public static Glucksspielthread[] players;
Then acces it in the Glucksspielthread class like this:
for (int i = 0; i <= playerNumber; i++) {
// here, I want to operate on array called "players" that is declared in the main method
Glucksspieltest.players
}
Add a method to class Glucksspieltest, and make the players array global:
public class Glucksspieltest {
private static Glucksspielthread[] players;
public static Glucksspielthread[] getPlayers(){
return players;
}
public static void main(String[] args) {
int numPlayers = Integer.parseInt(args[0]);
int threadSize = Integer.parseInt(args[1]);
ExecutorService es = Executors.newFixedThreadPool(threadSize);
players = new Glucksspielthread[numPlayers];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Glucksspielthread(i);
es.execute(players[i]);
}
}
}
This way you can get the array by calling the getPlayers() method.
(Note that, it would be adviced to add a constructor to initialize and fill the players array, and separate the player management from the main method as well.)
Make players as private global referance variable
public class Glucksspieltest {
//Make a Global reference variable players
private static Glucksspielthread[] players;
// Make a getter Method to get players
public static Glucksspielthread[] getPlayers(){
return players;
}
public static void main(String[] args) {
int numPlayers = Integer.parseInt(args[0]);
int threadSize = Integer.parseInt(args[1]);
ExecutorService es = Executors.newFixedThreadPool(threadSize);
players = new Glucksspielthread[numPlayers];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Glucksspielthread(i);
es.execute(players[i]);
}
}
}
And access it by Glucksspieltest.getPlayers();
class Glucksspielthread implements Runnable {
public int playerNumber;
private static Glucksspielthread[] players;
Glucksspielthread(int number) {
playerNumber = number;
}
#Override
public void run() {
for (int i = 0; i <= playerNumber; i++) {
// here, I want to operate on array called "players" that is declared in the main method
players= Glucksspieltest.getPlayers(); // play with players
}
}
}
I have an arraylist of Integers called stockList.
I want a primitive type of int[] stockListFinal to be made form the arrayList.
Code:
public class Warehouses {
ArrayList<Warehouse> warehouses = new ArrayList<Warehouse>();
ArrayList<Integer> stockList = new ArrayList<Integer>();
ArrayList<String> locationsList = new ArrayList<String>();
int[] stockListFINAL;
int[] locationsListFINAL;
public Warehouses() {
addWarehouses();
stockList();
locationList();
}
public void addWarehouses() {
//DATABASE WOULD BE SEARCHED FOR EACH PRESENT RECORD AND ADDED HERE
//FOR SIMPLICITY I HAVE DONE THIS MANUALLY
warehouses.add(new Warehouse("W1", 20, "RM13 8BB"));
warehouses.add(new Warehouse("W2", 28, "RM13 8BB"));
warehouses.add(new Warehouse("W3", 17, "RM13 8BB"));
}
public void stockList() {
for(Warehouse warehouse : warehouses) {
Integer stock = warehouse.getStock();
}
stockListFINAL = convertIntegers(stockList);
}
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i);
}
return ret;
}
public void locationList() {
for(Warehouse warehouse : warehouses) {
String location = warehouse.getLocation();
}
}
}
class Warehouse
{
private String warehouseID;
private int warehouseStock;
private String location;
/**
* Constructor for objects of class Warehouse
*/
public Warehouse(String warehouseID, int warehouseStock, String location)
{
// initialise instance variables
this.warehouseID = warehouseID;
this.warehouseStock = warehouseStock;
this.location = location;
}
public int getStock(){
return warehouseStock;
}
public String getLocation() {
return location;
}
}
stockListFinal however returns empty.
What has happened here?
If you run main in the class below you'll see the int[] is populated. This isn't how I'd recommend implementing, but I've tried to remain as close to your example as possible:
import java.util.ArrayList;
import java.util.List;
public class SE
{
final static ArrayList<Integer> stockList = new ArrayList<Integer>();
public static int[] convertIntegers(final List<Integer> integers)
{
final int[] ret = new int[integers.size()];
for (int i = 0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
public static void addStock()
{
stockList.add(20);
stockList.add(30);
}
public static void main(final String[] args)
{
addStock();
final int[] stockListFINAL = convertIntegers(stockList);
for (int i = 0; i < stockListFINAL.length; i++)
{
System.out.println(String.format(" For location %d in the int[] the value is %d", i, stockListFINAL[i]));
}
}
}
You didn't call addStock() so the List is empty.
addStock(); // this was missing, and it
// should probably take the
// List as an argument.
int[] stockListFINAL = convertIntegers(stockList);
I then verified with this code
// No change.
public static int[] convertIntegers(
List<Integer> integers) {
int[] ret = new int[integers.size()];
for (int i = 0; i < ret.length; i++) {
ret[i] = integers.get(i).intValue();
}
return ret;
}
// Made static, added List as argument.
public static void addStock(List<Integer> stockList) {
stockList.add(20);
stockList.add(30);
}
public static void main(String s[]) {
ArrayList<Integer> stockList = new ArrayList<Integer>();
addStock(stockList);
int[] stockListFINAL = convertIntegers(stockList);
System.out.println(java.util.Arrays.toString(stockListFINAL));
}
And it outputs -
[20, 30]
You never added Stock(s) to your List(s).