I am working on a class final. It is supposed to be a "Media Library" to stores information about a persons media(DVDs, games etc.) among other things it's supposed to take in new media items, store them to an array and display them when prompted. It does all of those but when it displays it has a NullPointerException on the getters even though it is executing it how I intended.
public class MediaItem {
private String title;
private String format;
private boolean onLoan;
private String loanedTo;
private String dateLoaned;
public MediaItem(){
title = null;
format = null;
onLoan = false;
loanedTo = null;
dateLoaned = null;
}
public MediaItem(String title, String format){
this.title = title;
this.format = format;
onLoan = false;
}
Above are the fields and constructors for the class that makes the "MediaItems" as we were told to call them
Below, parts of another class, that is the library itself. One array for storing the media items and one for printing out the list. Also the add method and how I have been adding them to the array.
private MediaItem[] items = new MediaItem[100];
private String[] listOfItems = new String[100];
private int numberOfItems = 0;
public void addNewItem(String title, String format){
MediaItem item = new MediaItem(title, format);
items[numberOfItems] = item;
numberOfItems++;
}
And here is the part I am having problems with
public void listAllItems(){
for (int i = 0; i < items.length; i++){
System.out.println(items[i].getTitle());
}
}
This isn't what its supposed to do, but my current problem is that it does print out the entire list of items but also gives a NullPointerException and I dont know why. The getter that is being called is a basic eclipse generated getter
public String getTitle() {
return title;
}
This is a Java I coarse so I'm new so please be gentle. I believe that is all the relevant parts so any help is appreciated!
items.length will always be the length of the entire array (100 in your case), nomatter how many items you have actually added. Try it like this:
public void listAllItems(){
for (int i = 0; i < numberOfItems; i++){
System.out.println(items[i].getTitle());
}
}
The problem in your case is not the getter itself but trying to call the getTitle() method on null.
You do have 100 places reserved but I suspect that not all the places are occupied. This causes the NullPointerException when accessing properties of these element.
You can use below method to get all non-null elements from the array:
public void listAllItems(){
int i = 0;
while (i < numberOfItems){
if (items[i] != null) // Null check
System.out.println(items[i].getTitle());
i+=1;
}
}
Or using the same 'for' loop with just the null check should also suffice:
public void listAllItems(){
for (int i = 0; i < numberOfItems; i++) {
if (items[i] != null)
System.out.println(items[i].getTitle());
}
}
Related
I have an object array containing two fields per object.
I have to write a method that will sort my array by the first field.
I already have a method which extracts the first field from each object
I always get an error message when I call my method to sort.
Here is my code:
public static void trier(String[]code, String[]nom, int nbObj) {
for(int i = 0; i < nbObj-1; i++) {
int indMin = i;
for (int j = i+1; j < nbObj; j++)
if (code[j].compareTo(code[indMin]) < 0)
indMin = j;
if (indMin != i) {
// permutation :
String tempo = code[i];
code[i] = code[indMin];
code[indMin] = tempo;
// permutation :
String temp = nom[i];
nom[i] = nom[indMin];
nom[indMin] = temp;
}
}
}
and the call :
Classe.trier(tableau, tableau, nbObj);
I also tried Class.sort(array.getCode(), array.getName(), nbStudent);
But I still have compilation errors
thank you in advance for your help
First of all, you don't have to use 2 separate arrays to contain your data. You can put everything in a single array, but better way is to use Java Collections. Perfect choice is ArrayList. However, you still better combine two fields into a single object. You can do it like this:
public class MyObject {
String code;
String nom;
MyObject(String code, String nom) {
this.code = code;
this.nom = nom;
}
}
Now you have a class containing 2 fields. Your aim is to sort a collection of such objects by their second field (nom). You can do this easily since Java 8:
public static void sort1(ArrayList<MyObject> list) {
list.sort((obj1, obj2) -> obj1.nom.compareTo(obj2.nom));
}
Or
public static void sort2(ArrayList<MyObject> list) {
list.sort(Comparator.comparing(MyObject::getNom));
} // However for this you need to add method getNom to MyObject
Remember to put your objects in the collection properly.
For example:
MyObject a = new MyObject("abc", "abide");
MyObject b = new MyObject("cab", "whatever you want");
ArrayList<MyObject> list = new ArrayList<>();
list.add(a);
list.add(b);
trier(list);
A few questions. I'm creating a method that searches through an array of element objects (where each element object has been initialized with [atomicNumber abbreviation name atomicWeight]). I also need to return 'a reference to the element'-- not exactly sure how to do this. The user inputs an abbreviation in main, then the findAbbreviation method is used on an array. The toString method formats and returns each datatype as a String. How might I search for the abbreviation position in any given object for the entire array. And how do I return a reference to that 'element' object.
public class PeriodicTable {
private final int MAX_ELEMENTS = 200;
private PeriodicElement[] table;
private int actualSize;
public PeriodicTable() throws IOException{
table = new PeriodicElement[MAX_ELEMENTS];
Scanner input = new Scanner(new File("file name here"));
int index = 0;
while(input.hasNext() && index < MAX_ELEMENTS) {
int aN = input.nextInt();
String abbr = input.next();
String name = input.next();
double aW = input.nextDouble();
table[index] = new PeriodicElement(aN, abbr, name, aW);
index++;
}
input.close();
actualSize = index;
}
public String findAbbreviation(String abbreviationP){
boolean found = false;
int index = 0;
while(found && index < MAX_ELEMENTS){
if (table[index] = table[abbreviationP]){
found = true;
return table[index].toString;
}
index++;
}
return null;
}
}
class PeriodicElement {
private int atomicNumber;
private String abbreviation, name;
private double atomicWeight;
public PeriodicElement(int atomicNumberP,
String abbreviationP, String nameP,
double atomicWeightP){
atomicNumber = atomicNumberP;
abbreviation = abbreviationP;
name = nameP;
atomicWeight = atomicWeightP;
}
First, you would need an array or collection of Elements. This could be an instance variable of the class you are currently writing which includes 'findAbbreviation'.
Second, an "Element" could simply have an attribute variable like "abbreviation" as an instance variable of the Element class, and you may just be able to call the findAbbreviation on the list and search for that abbreviation specifically in the abbreviation instance variable. It is unlikely that you could search on the actual name to find the abbreviation, because, for example: Gold's "abbreviation" is AU.
Could you show how your list of elements is defined as well as the class that defines the Elements?
If you are simply looking through a list of abbreviations of elements (as your current code suggests), you may just have to fix your current code to do an equals comparison correctly:
public String findAbbreviation(String abbreviationP){
boolean found = false;
int index = 0;
while(!found && index < MAX_ELEMENTS){ //this should be !found instead of found
if (table[index].equals(abbreviationP)) { // you previously had an assignment statement in this if
found = true;
return table[index].toString;
}
index++;
}
return null;
}
Updating answer to reflect update to the question:
First, you will need to provide a method in the PeriodicElement class to get the instance variable "abbreviation".
This is a standard "getter":
public String getAbbreviation() {
return abbreviation;
}
Second, you'll want to update your findAbbreviation method to utilize this new getter:
public PeriodicElement findAbbreviation(String abbreviationP){
boolean found = false;
int index = 0;
while(!found && index < MAX_ELEMENTS){ //this should be !found instead of found
if (table[index].getAbbreviation().equals(abbreviationP)) { // you previously had an assignment statement in this if
found = true;
return table[index]; //This will return the object at the index where it was found.
// Notice I also changed the return type on your function.
}
index++;
}
return null;
}
I'm getting an error like this: Type mismatch: cannot convert from String to produktas ... I'm looking for the solution everywhere, but It seems too difficult for me. Would appriciate any help
My function is:
public static produktas[] surasti(produktas G[], int n) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
produktas A[] = new produktas[5];
for (int j = 0; j < 5; j++) {
System.out.println("Kokio produkto ieskosime?");
String found = in.readLine();
for (int i = 1; i < n; i++) {
if (found.equals(G[i].gautiPav())) {
A[j] = G[i].gautiPav(); // error line
}
}
}
return A;
} catch(IOException ie) {
ie.printStackTrace();
}
return null;
}
And my array class looks like:
class produktas {
private String pavadinimas;
private String salis;
private Double svoris;
private Double kaina;
produktas() {}
produktas(String pav, String salis, double svoris, double kaina) {
pavadinimas = pav;
this.salis = salis;
this.svoris = svoris;
this.kaina = kaina;
}
public String gautiPav() {
return pavadinimas;
}
}
A is an array of "produktas". You are trying to assign a string into it, that is the String that is returned by your gautiPav() method.
Are you sure you didn't mean to write this instead?
A[j] = G[i]; // error line
If you're seeing strings like this: name.produktas#60e53b93 then you should override the Object.toString() method to return a more human readable string, a typical example might look like this. If you're using any modern IDE such as Eclipse there is a helper for this, for Eclipse: Source, Generate toString()...
#Override
public String toString() {
return String.format("[produktas: %s]", pavadinimas);
}
Following discussion in the chat, it seems like you want to return A as produktas, but write/view the guatiPav() method where you reference A. You either need to override toString() if you want A to be represented differently than a series of "random" output:
class produktas {
private String pavadinimas;
private String salis;
private Double svoris;
private Double kaina;
produktas() {}
produktas(String pav, String salis, double svoris, double kaina) {
pavadinimas = pav;
this.salis = salis;
this.svoris = svoris;
this.kaina = kaina;
}
public String gautiPav() {
return pavadinimas;
}
#Override
public String toString() {
return guatiPav(); // or "return pavadinimas;"
}
}
Or you want to call gautiPav() directly wherever you're referencing the elements of A. I highly recommend the latter approach, as an Object's toString() should be descriptive of the Object, not a single parameter it is comprised of.
Good day,
Here is my code:
public class ArrayDirectory implements Directory {
private int allocatedSize = 0;
public Entry[] entryDirectory = new Entry[allocatedSize];
#Override
public void addEntry(Entry newEntry) {
newEntry = findFreeLocation();
entryDirectory = Arrays.copyOf(entryDirectory,
entryDirectory.length + 1);
}
private Entry findFreeLocation() {
Entry returnedEntry = new Entry();
for (int i = 0; i < entryDirectory.length; i++) {
if (entryDirectory[i] == null) {
break;
}
returnedEntry = entryDirectory[i];
}
return returnedEntry;
}
I've made the size of the entryDirectory dynamic; it increments each time the addEntry method is used. However, when I am trying to call a method of an entry object from the entryDirectory array, a NullPointerException is thrown.
public static void main(String[] args) {
ArrayDirectory d = new ArrayDirectory();
d.addEntry(new Entry("Jack", "Jones", 1234));
d.addEntry(new Entry("Brad", "Jones", 1234));
d.addEntry(new Entry("Olga", "Jones", 1234));
System.out.println(d.entryDirectory[0].getInitials());
}
Here is the getInitials() method of the Entry object.
public Entry(String surname, String initials, int extension){
this.surname = surname;
this.initials = initials;
this.extension = extension;
}
public String getInitials() {
return initials;
}
You never assign anything as element of your array entryDirectory, so NullPointerException arises when you try to invoke getInitials() on null-value object entryDirectory[0].
Remember that if you use Arrays.copyOf(),
for any indices that are valid in the copy but not the original, the
copy will contain null
See Arrays javadoc
In addition to Philip Voronov's answer, your findFreeLocation method is also implemented incorrectly. Assuming null means an absence of value, the proper implementation should be like this:
private int findFreeLocation() {
for (int i = 0; i < entryDirectory.length; i++) {
if (entryDirectory[i] == null) {
return i
}
}
return -1;
}
You can then use it like this:
public void addEntry(Entry newEntry) {
int loc = findFreeLocation();
if (loc >= 0) {
entryDirectory[loc] = newEntry;
} else {
entryDirectory = Arrays.copyOf(entryDirectory, entryDirectory.length + 1);
entryDirectory[entryDirectory.length - 1] = newEntry;
}
}
That said, I highly suggest you use a built-in collection, like ArrayList, to handle automatically resizing arrays. They are much easier to use, and their performance is also better (increasing the array size by one means you have to resize every time an item is added, in comparison to ArrayList's implementation, which doubles the size every time it fills up).
I recently posted a question about getting a NullPointerException whenever I called an array of objects. I have traced the problem back to some disconnect between the main method providing the data and the method in question (Team.sortPlayers()) receiving the data.
public class Project3 {
public static void main(String[] args) {
Input3 input = new Input3();
Team teams[] = new Team[input.NUMBER_OF_TEAMS];
Player players[] = new Player[input.NUMBER_OF_PLAYERS];
String playas[] = new String[input.NUMBER_OF_PLAYERS];
String temp;
String name;
for ( int i=0 ; i<input.NUMBER_OF_TEAMS ; i++ ) {
name = input.getNextString();
System.out.println(name);
for ( int j=0 ; j<input.NUMBER_OF_PLAYERS ; j++ )
{playas[j] = input.getNextString();
System.out.println(playas[j]);}
teams[i] = new Team(name, playas); //THIS LINE SENDS OVER THE DATA TO THE QUESTIONABLE METHOD
teams[i].sortPlayers();
System.out.println(teams[i]);
}
}
}
//------------------------------
//
//------------------------------
class Player {
public String[] name;
public Player(String inputname) {
name = inputname.split(" ");
}
public String[] getName() {
return name;
}
public String getFirstName() {
return name[0];
}
public String getLastName() {
String last = name[1];
return last;
}
}
//-----------------------
//
//-----------------------
class Team {
private String teamname;
public Player players[];
public Player temp;
public Team(String inputname, String plays[]) { //THIS METHOD RECEIVES A NULL FOR 'INPUTNAME' AND WHAT APPEARS TO BE A JIBBERISH (ex: Player#5bdf59bd, maybe a memory address?) FOR 'PLAYS[]'
inputname = teamname;
System.out.println(teamname);
players = new Player [plays.length];
for( int k=0 ; k<plays.length ; k++ )
{ System.out.println(inputname);
this.players[k] = new Player(plays[k]);
System.out.println(players[k]);
}
}
public void sortPlayers() {
int n = players.length;
for (int pass=1; pass < n; pass++){
for (int i=0; i < n-pass; i++) {
String playerName = players[i].getLastName();
String nextPlayerName = players[i+1].getLastName();
if(playerName.compareTo(nextPlayerName) > 0)
temp = players[i];
players[i] = players[i+1];
players[i+1] = temp;
}
}
}
}
If anyone could help me figure what is going on here, I'd be very grateful! I've marked the two problematic statements with comments, and a PasteBin of it all can be found below:
http://pastebin.com/QGALKbP6
"temp" should not be a member variable, it should be local to the if block in the sort method. and, because if its expanded scope, you are inadvertently clearing some members of your players array due to the fact that your "if" block is missing some braces.
if(playerName.compareTo(nextPlayerName) > 0) {
Player temp = players[i];
players[i] = players[i+1];
players[i+1] = temp;
}
generally, even though braces are optional in some circumstances, you should use them all the time to avoid subtle bugs like this.