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.
Related
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.
I'm writing a program in java and i need to make a list whose nodes are another list . My code for the nodes of the sub list is this :
public class Page {
private String word;
private int num;
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public Page(String word, int num) {
this.word = word;
this.num = num;
}
}
My code for the nodes of my main list is :
import java.util.ArrayList;
public class IndPage {
private ArrayList<Page> Eggrafi;
//private ArrayList<Page> Eggrafi = new ArrayList<Page>();
public IndPage(String name, int bytes) {
Eggrafi = new ArrayList<Page>();
Eggrafi.add(new Page(name, bytes));
}
public ArrayList<Page> getEggrafi() {
return Eggrafi;
}
public void setEggrafi(ArrayList<Page> eggrafi) {
Eggrafi = eggrafi;
}
}
When i use in my main the following code to fill my list i get a java heap space exception:
if(Index.size()!=0){
for(int j=0;j<Index.size();j++){
for(int y=0;y<Index.get(j).getEggrafi().size();y++){
if((Index.get(j).getEggrafi().get(y).getWord()).equals(tokens[i-1])){
Index.get(j).getEggrafi().add(new Page(fileName[k],byte_count));
}
else{
Index.add(new IndPage(fileName[k],byte_count));
}
}
}
}
else{
Index.add(new IndPage(fileName[k],byte_count));
}
Also my main list is declared this way :
List<IndPage> Index = new ArrayList<IndPage>();
I've tried many things but still getting the java heap space exception .
Your issue is in your for loop:
for(int j=0;j<Index.size();j++){
for(int y=0;y<Index.get(j).getEggrafi().size();y++){
if((Index.get(j).getEggrafi().get(y).getWord()).equals(tokens[i-1])){
Index.get(j).getEggrafi().add(new Page(fileName[k],byte_count));
}
else{
Index.add(new IndPage(fileName[k],byte_count));
}
}
}
Your for loops are doing a check against the lists .size() function you are adding new items to those lists, so the .size() will always be at least 1 more than either the j or y index variables and the loops will never terminate. That eventually is running you out of heap space. The Index.size() and Index.get(j).getEggrafi().size() values are recalculated each time by the for loop, they are not cached.
I think you code is allocating a new list for every insert.
import java.util.List;
import java.util.ArrayList;
public class IndPage {
private List<Page> Eggrafi = new ArrayList<Page>();
public IndPage(final String name, final int bytes) {
Eggrafi.add(new Page(name, bytes));
}
public List<Page> getEggrafi() {
return Eggrafi;
}
public void setEggrafi(final List<Page> eggrafi) {
Eggrafi = eggrafi;
}
}
The code for the loops can be improved by using Java 5 style collection loops ie:
for (final Page page : Eggrafi) {
...
}
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");
pretty much I've made a program that goes a little like this
Players are added to an array
they are then all placed against each other(just like a football match, every team plays every team)
They are then randomized
the program should display the end result(if you win a game you get 3 points) etc..
I keep getting a message from Eclipse saying ".setScore has NOT been coded..
TestGame.java
public class TestGame {
static Players ceri = new Players("Ceri", 0);
static Players harry = new Players("Harry", 0);
static Players matthew = new Players("Matthew", 0);
static Players james = new Players("James",0);
static Players kwok = new Players("Kwok",0);
static Players lewis = new Players("Lewis",0 );
static Game League = new Game();
int Ceri = 0;
public static void main(String[] args) {
League.addPlayers(ceri);
League.addPlayers(matthew);
League.addPlayers(james);
League.addPlayers(kwok);
League.addPlayers(lewis);
League.addPlayers(harry);
League.randomize();
League.Results();
}
}
Game.java
public class Game extends TestGame {
Scanner s = new Scanner(System.in);
private Players[] people = new Players[6];
private int counter = 0;
List<String> Matches = new ArrayList<String>();
public void addPlayers(Players obj){
people[counter] = obj;
counter++;
System.out.println(obj.getName());
}
public String randomize(){
for(int i = 0; i < people.length; i++){
for(int j = i + 1; j < people.length; j++){
if(people[i].equals(people[j].getName())){
continue;
} else {
Matches.add(people[i].getName() + " V " + people[j].getName());
}
}
}
return null;
}
public String Results(){
while(!Matches.isEmpty()){
int Game = (int)(Math.random() * Matches.size());
String Verses = (String)Matches.get(Game);
System.out.println(Verses);
System.out.println("Who has won?");
String name = s.nextLine();
//**ISSUE LIES HERE**
if(Verses.contains(name)){
if(name == "ceri"){
ceri.setScore(3);
} else if(name == "harry"){
harry.setScore(3);
}else if (name == "matthew"){
matthew.setScore(3)
} else if(name == "lewis"){
lewis.setScore(3)
}else if ( name == "james"){
james.setScore(3)
}else if(name == "kwok"){
kwok.setScore(3);
}
}
Matches.remove(Game);
System.out.println(one);
return null;
}
return null;
}
}
WHERE ECLIPSE SAYS .setScore ISNT.
Players.java
public class Players {
private String name;
private int score;
public Players(String name, int score){
this.name = name;
this.score = score;
}
public String getName(){
return this.name;
}
public int getScore() {
return this.score;
}
public void setScore(int score) {
this.score =+ score;
}
}
All the players are static members of TestGame class. They can access only static methods of Players now. So that is why you are getting the error.
First off, there are compile errors. Please see merlin2011's answer for reference.
As to your actual issue, your Players (ceri, harry, matthew, etc.) are static members of TestGame...but are not publicly exposed. This means that other objects can't see them, and so can't access them. Add the public keyword to them:
public class TestGame {
public static Players ceri = new Players("Ceri", 0);
public static Players harry = new Players("Harry", 0);
public static Players matthew = new Players("Matthew", 0);
public static Players james = new Players("James",0);
public static Players kwok = new Players("Kwok",0);
public static Players lewis = new Players("Lewis",0 );
...
}
Now that they are publicly exposed, you need to reference them correctly. Your Game class doesn't know what ceri is when you call setScore(3), Since it is not a member of that class. Instead, you need to tell it where ceri is located; in your TestGame class. For reference, I've also used the traditional string equality comparison function.
if(name.equals("ceri")){
TestGame.ceri.setScore(3);
}
Use this format for the other IF statements you have.
Your code has a couple of issues, but neither of them is related to setScore not being defined.
You are missing semicolons in the following block.
if(Verses.contains(name)){
if(name == "ceri"){
ceri.setScore(3);
} else if(name == "harry"){
harry.setScore(3);
}else if (name == "matthew"){
matthew.setScore(3)
} else if(name == "lewis"){
lewis.setScore(3)
}else if ( name == "james"){
james.setScore(3)
}else if(name == "kwok"){
kwok.setScore(3);
}
}
You are not using equals for String comparison in the block above.
Here is a corrected version:
if(Verses.contains(name)){
if(name.equals("ceri")){
ceri.setScore(3);
} else if(name.equals("harry")){
harry.setScore(3);
} else if (name.equals("matthew")){
matthew.setScore(3);
} else if(name.equals("lewis")){
lewis.setScore(3);
} else if ( name.equals("james")){
james.setScore(3);
} else if(name.equals("kwok")){
kwok.setScore(3);
}
}
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