I am having troubles writing a test driver - java

my first time reaching out for help to solve a question, not sure what is causing the issue. I have these two classes I wrote, and the assignment asks me to make a test driver proving that the classes work.
Student Class:
public class Student{
private Course[] courseList;
private static int numCourses;
private final int maxCourses;
public Student(int max){
maxCourses = max;
courseList = new Course[numCourses];
numCourses = 0;
}
// part 1, done
public boolean addCourse(Course newClass){
boolean success = false;
for(int i=0; i<=maxCourses; i++){
if(i == numCourses){
courseList[i] = newClass;
success = true;
numCourses++;
}
}
return success;
}
// part 2, done
public boolean dropCourse(Course oldClass){
boolean success = false;
for(int i=0; i<=courseList.length; i++){
if (courseList[i] == oldClass){
courseList[i] = null;
numCourses--;
success = true;
}
}
return success;
}
// part 3, done.
public int getNumCourses(){
return numCourses;
}
//part 4, done
public boolean isFullTime(){
boolean success = false;
if (numCourses >= 3){
success = true;
}
return success;
}
// part 5, done
public String getClassList(){
String list = "";
for(int i=0;i<=numCourses; i++){
list = courseList[i].getID() + "\t" + courseList[i].getName() + "\n";
}
return list;
}
}
and a Course class:
public class Course{
private String name;
private int id;
private static int nextID = 200000;
public Course(String nameIn)
{
name = nameIn;
id = nextID;
nextID++;
}
public String getName(){
return name;
}
public int getID(){
return id;
}
}
For some reason if I make a test driver even one as simple as:
public class tester{
public static void main(String[] args){
Course one = new Course(Java);
}
}
I receive an error at my parameter saying cannot find symbol
javac tester.java
tester.java:6: error: cannot find symbol
one = new Course(name);
^
symbol: variable name
location: class tester
1 error
I had a much longer test driver but it did not make it past the first few lines as this was the same error just several of the same error.
Thanks for your time.
EDIT: I had put the Student class in twice by mistake, in my short test driver the only class in use is the Course class.

The problem is that because there are not quotes around Java, the compiler takes it as a variable name. Since it is undefined, the compiler cant find it. Use Course one = new Course("Java");

Related

Problems creating an object using a class and then putting it on a array

So I'm trying to do a User class and then trying to do an array for it
however every time I create a student it don't add to the array.
I tried to change names etc but its really a problem in code.
public class UsersList {
User student;
User[] studentList = new User[49];
public UsersList() {
}
public void createUser(int userNumber) {
String numberToString = String.valueOf(userNumber);
if (numberToString.length() == 9) {
for (int i = 0; i < 49; i++) {
if (studentList[i] == null) {
studentList[i] = new User(userNumber);
}
}
}
}
}
public class User {
public int userNumber;
private boolean isolation;
private String state;
public User(int number) {
userNumber = number;
isolation = false;
}
}
If someone can help me I would be greatful.
I added the following simple test method to UsersList class to demonstrate that the code is fine and you need to provide appropriate userNumber value when calling createUser method:
public static void main(String[] args) {
UsersList list = new UsersList();
int userNumber = 1;
list.createUser(userNumber); // insufficient length
System.out.printf("all nulls for %d? %s%n", userNumber, Arrays.stream(list.studentList).filter(Objects::isNull).count() == list.studentList.length);
userNumber = 123_456_789;
list.createUser(userNumber); // length of the number is 9
System.out.printf("no nulls for %d? %s%n", userNumber, Arrays.stream(list.studentList).filter(Objects::nonNull).count() == list.studentList.length);
}
Output:
all nulls for 1? true
no nulls for 123456789? true
However, you may want also to initialize the instance variable student.

Printing job status only once based on the status

I'm new to Java and I would like to ask a more theoretical question. I'm trying to add a new feature on a working program which is written in Java. The purpose of the program is to run multiple jobs in the background and check their status. The status could be "Ready", "Waiting", "Running", "Stopped", "Done". I would like to create a method which will print some information to the output, which is based on the status of the running jobs. The rules for the printing:
For the first time of checking the job, it should print: "Started: " + job.getName().
If job is stopped it should print "Failed: " + job.getName().
If job is done running it should print "Done: " + job.getName().
In the job class I declared two variables:
private boolean startDisplay = false;
private boolean endDisplay = false;
I did a loop through all jobs and check their status and print the proper message for each case. Also, I updated the variables to be true. But the problem is it prints the same string over and over. So I made those variables static:
private static boolean startDisplay = false;
private static boolean endDisplay = false;
But, in this way it will print start and end for only one job (and not for the others).
How can I print every message only once? I thought of using the hashmap but it does not feel the right OOP way.
From What I guess you need a POJO class something like following :
package com.stackoverflow;
public class Job {
private String jobName;
private boolean startDisplay = false;
private boolean endDisplay = false;
private boolean doneDisplay = false;
public Job(String jobName) {
this.jobName = jobName;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public boolean isStartDisplay() {
return startDisplay;
}
public void setStartDisplay(boolean startDisplay) {
this.startDisplay = startDisplay;
}
public boolean isEndDisplay() {
return endDisplay;
}
public void setEndDisplay(boolean endDisplay) {
this.endDisplay = endDisplay;
}
public boolean isDoneDisplay() {
return doneDisplay;
}
public void setDoneDisplay(boolean doneDisplay) {
this.doneDisplay = doneDisplay;
}
}
And a Class to manage your POJO :
package com.stackoverflow;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
List<Job> jobs = new ArrayList<>();
for (int i = 0; i < 5; i++) {
jobs.add(new Job("Job" + (i+1)));
}
String prompt = "";
while (!prompt.equals("q")) {
Scanner scanner = new Scanner(System.in);
prompt = scanner.nextLine();
if (prompt.equals("q"))
System.out.println("Bye");
if (prompt.equals("1")) {
System.out.println("Checking Job1 " + jobs.get(0).getJobName());
System.out.println("Started: " + jobs.get(0).isStartDisplay());
System.out.println("Done: " + jobs.get(0).isDoneDisplay());
System.out.println("Finished: " + jobs.get(0).isEndDisplay());
System.out.println("Changing State of the job....");
jobs.get(0).setStartDisplay(true);
}
}
}
}
Try to declare the boolean variables with the volatile keyword. Otherwise the main thread will not reliably see the changes made by the other threads.

Changing data in linkedlist java

I am trying to change the data portion of a node, but I am getting a cannot find symbol error on my sets and gets for the WordItem class. The first part is the object class and the containsWord is in the LinkedList class. Any help would be appreciated.
public class WordItem implements Comparable {
private String word;
private int count;
private ArrayList<Integer> atLines;
public WordItem(String word, int c, int atLine) {
this.word = word;
this.count = c;
this.atLines = new ArrayList<Integer>();
atLines.add(atLine);
}
#Override
public int compareTo(Object other) {
WordItem w = (WordItem)other;
return w.getWord().compareTo(this.word);
}
public String getWord() {
return this.word;
}
public int getCount() {
return this.count;
}
public void setCount(int count){
this.count = count;
}
public void setAtLines(int line){
this.atLines.add(line);
}
public boolean containWord(String word, int atLine){
Node curr,prev;
boolean flag = false;
prev = head;
for(curr = head.next; curr != null; curr = curr.next){
if(word.equals(curr.data.getWord())){
ArrayList<Integer> ara = curr.data.getLines();
for(int i = 0; i < ara.size(); i++){
if(ara.get(i) == atLine){
curr.data.setCount(curr.data.getCount() + 1);
return true;
}
}
curr.data.setAtLines(atLine);
curr.data.setCount(curr.data.getCount() + 1);
return true;
}
prev = curr;
}
return false;
}
I don't see any problems in the code. I ran it and I can't reproduce the error.
It might be that your IDE got stuck. Try to Clean/Build and if that doesn't help try resetting/clearing the cache (google for that, how to do that is different with every IDE).
From the code you have posted, there is no method WordItem#getLines().
I assume that you may have just not copied all the code in your question, but just to make sure that you do have this method within your WordItem class
public ArrayList<Integer> getLines(){
return atLines;
}
If not then the following line
ArrayList<Integer> ara = curr.data.getLines();
will fail.
I think you maybe have a little typo somewhere, if you see the definition of the error: http://java.about.com/od/cerrmsg/g/Definition-Cannot-Find-Symbol.htm
That may be the problem

Calling variables between different classes through methods

I'm doing an assignment for my computer science class.
I've done quite a bit of the assignment, but I'm having a little bit of trouble pulling the individual variables from the classes. We are just getting into classes and objects and this is our first assignment regarding them so I don't completely understand all of it. So far I've been able to print out the teams, but I haven't been able to pull the individual wins, losses, OTL and OTW so that I can compute whether or not each individual team is a winning team.
What I have done so far is create a class called winningRecord and getPoints, which returns a boolean deciding whether it's a winning team or not. (The formula for a winning team is if the points are > Games Played * 1.5 (as that is an even record).
I don't know how to pull the stats, as it has to be written in the HockeyTeam class. I have set it up so that the constructor sets the variables publicly so that the can be accessed, but as far as accessing them, I'm stumped.
As far as storing them once I am able to access them, would I just make a parallel method that has the points for each team, with just one digit assigned to each bin?
Here is all of the code, thanks for looking.
public class A1Q2fixed {
public static void main(String[] parms) { // main method
processHockeyTeams();
}
/*****************************/
public static void processHockeyTeams() { // processing method
boolean[] winningRecord;
HockeyTeam[] hockeyTeams;
hockeyTeams = createTeams();
printTeams(hockeyTeams);
System.out.print("*********************\n");
printWinningTeams();
winningRecord = HockeyTeam.winningRecord(hockeyTeams);
// printWinningTeams(hockeyTeams);
}
/*********************************/
public static void printTeams(HockeyTeam[] hockeyTeams) {
for (int i = 0; i < hockeyTeams.length; i++) {
System.out.println(hockeyTeams[i]);
}
}
public static void printWinningTeams() {
}
public static HockeyTeam[] createTeams() {
HockeyTeam[] teams;
HockeyTeam team;
int count;
teams = new HockeyTeam[HockeyTeams.getNumberTeams()];
team = HockeyTeams.getTeam();
for (count = 0; (count < teams.length) && (team != null); count++) {
teams[count] = team;
team = HockeyTeams.getTeam();
}
return teams;
}
}
/* hockey team class *******/
class HockeyTeam {
public String name;
public int wins;
public int otw;
public int otl;
public int losses;
public HockeyTeam(String name, int wins, int otw, int otl, int losses) {
this.name = name;
this.wins = wins;
this.otw = otw;
this.otl = otl;
this.losses = losses;
}
public String toString() {
System.out.println(name);
return " W:" + wins + " OTW:" + otw + " OTL:" + otl + " L:" + losses;
}
public static boolean[] winningRecord(HockeyTeam[] hockeyTeam) {
boolean array[] = new boolean[hockeyTeam.length];
String name;
int wins;
int otw;
int otl;
int losses;
for (int i = 0; i < hockeyTeam.length; i++) {
System.out.println(HockeyTeam.name);
}
return array;
}
public static int getPoints() {
int points = 0;
return points;
}
}
/* hockey teams class *******************/
class HockeyTeams {
private static int count = 0;
private static HockeyTeam[] hockeyTeams = {
new HockeyTeam("Canada", 5, 3, 0, 0),
new HockeyTeam("Russia", 5, 1, 1, 2),
new HockeyTeam("Finland", 3, 2, 1, 3),
new HockeyTeam("Sweden", 4, 1, 1, 4),
new HockeyTeam("USA", 1, 2, 2, 3), };
public static int getNumberTeams() {
return hockeyTeams.length;
}
public static HockeyTeam getTeam() {
HockeyTeam hockeyTeam;
hockeyTeam = null;
if (count < hockeyTeams.length) {
hockeyTeam = hockeyTeams[count];
count++;
}
return hockeyTeam;
}
}
Thanks,
Matt.
Sorry but I was only able to understand only a part of your question,from what I understood it seems you are not able to access individual wins, losses, OTL and OTW. I hope this answers your question if not please clarify a bit
To access OTL,OTW have a loop as below:
public class A1Q2fixed
{
public static void main(String[] parms) // main method
{
processHockeyTeams();
}
/*****************************/
public static void processHockeyTeams() // processing method
{
boolean[] winningRecord;
HockeyTeam[] hockeyTeams;
hockeyTeams = createTeams();
printTeams(hockeyTeams);
System.out.print("*********************\n");
printWinningTeams();
winningRecord = HockeyTeam.winningRecord(hockeyTeams);
for(HockeyTeam h:hockeyTeams)
{
System.out.println(h.losses);//To access and print losses
System.out.println(h.otw);//To access and print otw
System.out.println(h.otl);//To access and print otl
}
// printWinningTeams(hockeyTeams);
}
/*********************************/
public static void printTeams(HockeyTeam[] hockeyTeams)
{
for (int i = 0; i < hockeyTeams.length; i++)
{
System.out.println(hockeyTeams[i]);
}
}
public static void printWinningTeams()
{
}
public static HockeyTeam[] createTeams()
{
HockeyTeam[] teams;
HockeyTeam team;
int count;
teams = new HockeyTeam[HockeyTeams.getNumberTeams()];
team = HockeyTeams.getTeam();
for (count=0; (count<teams.length) && (team!=null); count++)
{
teams[count] = team;
team = HockeyTeams.getTeam();
}
return teams;
}
}
Also declare name as Static in HockeyTeam

Homework: "Exception in thread "main" java.lang.NullPointerException"

Okay so I have a homework assignment. I thought I had everything good on it, and I am getting an
"Exception in thread "main" java.lang.NullPointerException at HW3.main<HW3.java:18>
That line is:
tempMembers[i/4].setFirstName(args[i]);
Now I am still pretty much a noob at programming, and everything up until this point I have done was in Eclipse. This program was to be created in a text editor and then compiled and ran at the command prompt. I do not know if maybe I am just inputting the arguments incorrectly or what not.
So for this error my command prompt entry was
java HW3 Bill Smith 2009 Football Jane Doe 2000 Tennis David Jones 1995 Baseball
So is the error in my code or in my input? And if the error is in my code can you point me in the correct direction? Like I said command line arguments are completely new to me, and my class doesn't do examples of any of this, just talks about concepts.
public class HW3 {
public static void main(String[] args) throws Exception {
if (args.length % 4 != 0) {
throw new Exception(
"First Name, Last Name, Year Inducted, Sport not entered correctly");
}
HallOfFame hallOfFameList = new HallOfFame();
hallOfFameList.setNumberOfMembers(args.length / 4);
HallOfFameMember[] tempMembers = new HallOfFameMember[args.length / 4];
for (int i = 0; i < args.length; i += 4) {
tempMembers[i/4].setFirstName(args[i]);
tempMembers[i/4].setLastName(args[i+1]);
tempMembers[i/4].setYearInducted(Integer.parseInt(args[i+2]));
tempMembers[i/4].setSport(args[i+3]);
}
hallOfFameList.setMembers(tempMembers);
HallOfFameMember[] sortedMembers = null;
hallOfFameList.sortMembers(sortedMembers);
HallOfFame.printReport(sortedMembers);
}
}
public class HallOfFameMember implements Comparable<HallOfFameMember> {
private String firstName;
private String lastName;
private String sport;
private int yearInducted;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
public int getYearInducted() {
return yearInducted;
}
public void setYearInducted(int yearInducted) {
this.yearInducted = yearInducted;
}
#Override
public int compareTo(HallOfFameMember o) {
return this.getYearInducted() - o.getYearInducted();
}
}
public class HallOfFame {
private HallOfFameMember[] members;
private int numberOfMembers;
public HallOfFameMember[] getMembers() {
return members;
}
public void setMembers(HallOfFameMember[] members) {
this.members = members;
}
public int getNumberOfMembers() {
return numberOfMembers;
}
public void setNumberOfMembers(int numberOfMembers) {
this.numberOfMembers = numberOfMembers;
}
public void sortMembers(HallOfFameMember[] sortedMembers) {
boolean bool = true;
HallOfFameMember temp;
while (bool) {
bool = false;
for (int i = 0; i < sortedMembers.length - 1; i++) {
if (sortedMembers[i].compareTo(sortedMembers[i + 1]) > 0) {
temp = sortedMembers[i];
sortedMembers[i] = sortedMembers[i + 1];
sortedMembers[i + 1] = temp;
bool = true;
}
}
}
}
public static void printReport(HallOfFameMember[] print) {
System.out.println("Java Sports Hall of Fame Inductees\n\n");
System.out.printf("%-30s\t%-30s\t%-30s\n", "Name", "Year Inducted",
"Sport");
for (int i = 0; i < print.length; i++)
System.out.printf("%-30s\t%-30s\t%-30s\n", print[i].getLastName()
+ "," + print[i].getFirstName(),
print[i].getYearInducted(), print[i].getSport());
}
}
You initialised your array on this line:
HallOfFameMember[] tempMembers = new HallOfFameMember[args.length / 4];
but the array will contain null elements. You need to construct each element in the array before you try to call methods on it:
tempMembers[i/4] = new HallOfFameMember();
tempMembers[i/4].setFirstName(args[i]);
When you declare tempMembers, you initialize the array but not the elements. Add this to your for loop:
tempMembers[i / 4] = new HallOfFameMember();
Then you'll get another NPE because sortedMembers is null (as you are explicitly setting it to be).
I also notice some other strange areas in your code. For example, in HallOfFame#sortMembers(HallOfFameMember[]), why do you use a while loop that will run exactly once in any condition (setting bool to true beforehand and false during the loop)?
Change the last four lines to :
hallOfFameList.setMembers(tempMembers);
final HallOfFameMember[] sortedMembers = tempMembers;
hallOfFameList.sortMembers(tempMembers);
HallOfFame.printReport(sortedMembers);
to resolve the last exception and get the desired output.
The exception means that tempMembers[i/4] evaluates to null, and when you try to call a method on null, you get a NullPointerException. In this case, you're getting it because you haven't actually put anything into tempMembers yet. In Java, creating an array doesn't populate it. Creating the array with new HallOfFameMember[args.length / 4] creates a new array of some length with all of its positions set to null. So after creating the array, you need to create and store a new HallOfFameMember in each array position.

Categories