Getter, Setter & NullPointerException - java

Firstly, I am trying to assign the value for array I initialized locally. The class type of the array is stored inside another class and the variable is private so I am using getter and setter to set the value. But it showing "Exception in thread "main" java.lang.NullPointerException at room.Test.main(Test.java:26)", below is my code for the test.java:
public class Test {
public static void main(String[] args) {
Room[] room = new Room[72];
Integer i = 0;
try {
File RoomTxt = new File("Room.txt");
Scanner read = new Scanner(RoomTxt);
while (read.hasNextLine()) {
room[i].setRoomID(read.next());
room[i].setRoomType(read.next() + " " + read.next());
room[i].setFloor(read.nextInt());
room[i].setRoomStatus(read.nextInt());
read.nextLine();
i++;
}
read.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
Below is the class I used to store the Room type:
public class Room {
private String roomID;
private String roomType;
private Integer floor;
private Integer roomStatus;
//Setter
public void setRoomID(String roomID) {
this.roomID = roomID;
}
public void setRoomType(String roomType) {
this.roomType = roomType;
}
public void setFloor(Integer floor) {
this.floor = floor;
}
public void setRoomStatus(Integer roomStatus) {
this.roomStatus = roomStatus;
}
//Getter
public String getRoomID() {
return this.roomID;
}
public String getRoomType() {
return this.roomType;
}
public Integer getFloor() {
return this.floor;
}
public Integer getRoomStatus() {
return this.roomStatus;
}
}
PS. The records stored inside my Room.txt is like
RS11 Single Room 1 1
RD12 Double Room 1 0

You need to write room[I] = new Room(); before you start calling its setters.

Initializing an array only assigns the array reference to a new array object of the given type and allocates the array memory space.
Array elements reference is initialized to default element type values i.e.:
null for Object and String types
0 for numeric values
false for boolean ones
Hence all the room[i] elements refers to null.
You should be assigning element values before calling any method over these (including setters):
public class Test {
public static void main(String[] args) {
Room[] room = new Room[72];
Integer i = 0;
try {
File RoomTxt = new File("Room.txt");
Scanner read = new Scanner(RoomTxt);
while (read.hasNextLine()) {
room[I] = new Room();
// set the field values
}
read.close();
} catch (FileNotFoundException e) {
// ...
}
}

Related

How to get user input and store in custom object? JAVA

Henlo,
Basically what im trying to do is get user inputs and store in a custom object but I have no idea on how to go about it. I have created a loadDataFromConfig() method? that works fine when creating the object SmartHome app = new SmartHome(loadDataFromConfig());.
But I am completely stumped on how to get user inputs and store them in this format: dev[0] = new SmartDevice("device 1",1.3,true);.
All the code that is meant to run should be inside the main method in Step1.java
Here are the 3 classes used for the code (ignore comments they are just notes for me):
package SmartHomeApp;
public class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String val1, double val2, boolean val3) {
setName(val1);
setLocation(val2);
setSwitchedOn(val3);
}
//YOU CANT ACCESS the 'private classes' so you need to GET them
public void setName(String value) {name = value;}
public void setLocation(double value) {location = value;}
public void setSwitchedOn(boolean value) {switchedOn = value;}
public String getName() {return name;}
public double getLocation() {return location;}
public boolean getSwitchedOn() {return switchedOn;}
}
package SmartHomeApp;
public class SmartHome
{
private SmartDevice[] smrtDev;
public SmartHome(int size) {
smrtDev = new SmartDevice[size];
}
public SmartHome(SmartDevice[] values) {
smrtDev = values;
}
public int size() {return smrtDev.length;}
// can't do toString() for some reason??
public void ToString() {
for(int i=0; i<size();i++)
{
if(smrtDev[i] != null ){
System.out.println("----------");
System.out.println("-DEVICE "+(i+1)+"-");
System.out.println("----------");
System.out.println("Name: "+smrtDev[i].getName());
System.out.println("Location: "+smrtDev[i].getLocation());
System.out.println("Switched On: "+smrtDev[i].getSwitchedOn());
}
}
}
}
package SmartHomeApp;
import java.util.*;
public class Step1 {
public static void main(String args[]) {
SmartHome app = new SmartHome(loadDataFromConfig());
app.ToString();
}
public static SmartDevice[] loadDataFromConfig()
{
SmartDevice[] dev = new SmartDevice[20];
dev[0] = new SmartDevice("device 1",1.3,true);
dev[1] = new SmartDevice("device 2",2.3,false);
dev[2] = new SmartDevice("device 3",3.3,true);
dev[4] = new SmartDevice("device 5",4.3,false);
dev[19] = new SmartDevice("device 20",5.3,false);
return dev;
}
}
Some of the improvements required in your code are as follows:
Follow Java naming conventions e.g. ToString() should be toString(). Check this to learn more about toString(). Most of the IDEs (e.g. eclipse) provide a feature to generate toString() method on click of a button. Whatever way (either manual or with the help of your IDE) you generate it, it must return a String.
You should do away with using next(), nextInt(), nextDouble() etc. and use nextLine() instead. Check this to learn more it. To give you an idea what problems next(), nextDouble() can cause, try entering a name with a space e.g.
Enter size:
2
Name:
Light Amplification by Stimulated Emission of Radiation
Location:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Main.main(Main.java:83)
Given below is a sample code incorporating the improvements mentioned above:
import java.util.Scanner;
class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String val1, double val2, boolean val3) {
setName(val1);
setLocation(val2);
setSwitchedOn(val3);
}
// YOU CANT ACCESS the 'private classes' so you need to GET them
public void setName(String value) {
name = value;
}
public void setLocation(double value) {
location = value;
}
public void setSwitchedOn(boolean value) {
switchedOn = value;
}
public String getName() {
return name;
}
public double getLocation() {
return location;
}
public boolean getSwitchedOn() {
return switchedOn;
}
#Override
public String toString() {
return "SmartDevice [name=" + name + ", location=" + location + ", switchedOn=" + switchedOn + "]";
}
}
class SmartHome {
private SmartDevice[] smrtDev;
public SmartHome(int size) {
smrtDev = new SmartDevice[size];
}
public SmartHome(SmartDevice[] values) {
smrtDev = values;
}
public int size() {
return smrtDev.length;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (SmartDevice smartDevice : smrtDev) {
sb.append(smartDevice.toString()).append("\n");
}
return sb.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
int size = getPositiveInt(myObj, "Enter size: ");
SmartDevice[] newList = new SmartDevice[size];
for (int i = 0; i < newList.length; i++) {
System.out.print("Name: ");
String x = myObj.nextLine();
double y = getFloatingPointNumber(myObj, "Location: ");
boolean z = getBoolean(myObj, "Is on?: ");
newList[i] = new SmartDevice(x, y, z);
}
SmartHome newDevice = new SmartHome(newList);
System.out.println(newDevice);
}
static int getPositiveInt(Scanner in, String message) {
boolean valid;
int n = 0;
do {
valid = true;
System.out.print(message);
try {
n = Integer.parseInt(in.nextLine());
if (n <= 0) {
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException e) {
System.out.println("This in not a positive integer. Please try again.");
valid = false;
}
} while (!valid);
return n;
}
static double getFloatingPointNumber(Scanner in, String message) {
boolean valid;
double n = 0;
do {
valid = true;
System.out.print(message);
try {
n = Double.parseDouble(in.nextLine());
} catch (NumberFormatException | NullPointerException e) {
System.out.println("This in not a number. Please try again.");
valid = false;
}
} while (!valid);
return n;
}
static boolean getBoolean(Scanner in, String message) {
System.out.print(message);
return Boolean.parseBoolean(in.nextLine());
}
}
A sample run:
Enter size: x
This in not a positive integer. Please try again.
Enter size: -2
This in not a positive integer. Please try again.
Enter size: 10.5
This in not a positive integer. Please try again.
Enter size: 2
Name: Light Amplification by Stimulated Emission of Radiation
Location: 123.456
Is on?: true
Name: Vacuum Diode
Location: 234.567
Is on?: no
SmartDevice [name=Light Amplification by Stimulated Emission of Radiation, location=123.456, switchedOn=true]
SmartDevice [name=Vacuum Diode, location=234.567, switchedOn=false]
So as suggested I tried to do the following:
public static void main(String args[]) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter size: ");
int size = myObj.nextInt();
SmartDevice[] newList = new SmartDevice[size];
for(int i =0; i<newList.length;i++) {
System.out.println("Name: ");
String x = myObj.next();
System.out.println("Location: ");
double y = myObj.nextDouble();
System.out.println("Is on?: ");
boolean z = myObj.nextBoolean();
newList[i] = new SmartDevice(x,y,z);
}
SmartHome newDevice = new SmartHome(newList);
newDevice.ToString();
}
Got it working but not sure if this is the most efficient way to do so??

(identifier expected) getter/setter and objects

I've got a problem with my programm. When i try to compile following i just receive the message:
Tutorium.java:15: error: <identifier> expected
public void settName(vorlesung.lectureName) {
^
So my Code:
Tutorium.java
public class Tutorium {
private Vorlesung vorlesung;
public String tName;
private int tNumber;
public int gettNumber() {
return this.tNumber;
}
public String gettName() {
return this.tName;
}
public void settName(vorlesung.lectureName) {
this.tName = vorlesung.lectureName;
}
public String toString() {
return (this.tName + ", " + this.tNumber);
}
public Tutorium(int tNumber){
this.tNumber = tNumber; } }
Vorlesung.java
public class Vorlesung {
public String lectureName;
private int lectureNumber;
private int lecture;
private Dozent dozent;
private String lecturerlName;
public String getlectureName(){
return this.lectureName;
}
public int lectureNumber(){
return this.lectureNumber;
}
public int lecture(){
return this.lecture;
}
public String getlecturer(){
this.lecturerlName = dozent.lecturerlName;
return this.lecturerlName;
}
public String toString() {
return (this.lectureName + ", " + this.lectureNumber);
}
public Vorlesung(String lectureName, int lecture) {
this.lectureName = lectureName;
this.lecture = lecture +1;
this.lectureNumber = this.lecture -1;
this.lecturerlName = lecturerlName;
}}
My Main-Method:
public class MainVorlesung {
public static void main(String[] args) {
Student student = new Student("STUDENTNAME", "STUDENTLASTNAME", 178, 1);
Vorlesung vorlesung = new Vorlesung("Programmieren", 13341);
Tutorium tutorium = new Tutorium(3);
Dozent dozent = new Dozent("LECTURERFIRSTNAME", "LECTURERLASTNAME", 815);
System.out.println(student.toString());
System.out.println(vorlesung.toString());
System.out.println(tutorium.toString());
System.out.println(dozent.toString());
}}
My goal is to set the value of tName equal the value of vorlesung.lectureName.
Why can't i do this that way?
I appreciate every help. :)
Thanks
For methods, the arguments that you pass in must have a declared value.
In this case, a String. So you need to change your method to this:
public void settName(String newLectureName) {
this.tName = newLectureName;
}
Read more about what a java method is and how to create one here: http://www.tutorialspoint.com/java/java_methods.htm
Change settName to
public void settName(String name) {
this.tName = name;
}
Since your goal is:
My goal is to set the value of tName equal the value of vorlesung.lectureName.
You should get rid of the setName method entirely since it will depend entirely on the vorlesung field and so should not be changeable. You should also get rid of the tName field, and instead change getName() to:
public class Tutorium {
private Vorlesung vorlesung;
// public String tName; // get rid of
private int tNumber;
public String gettName() {
if (vorlesung != null) {
return vorlesung.getlecturer();
}
return null; // or throw exception
}
// *** get rid of this since you won't be setting names
// public void settName(Vorlesung vorlesung) {
// this.tName = vorlesung.lectureName;
// }
I have just now noticed that your Tutorium class does not have and absolutely needs a setVorlesung(...) method.
public void setVorlesung(Vorlesung vorlesung) {
this.vorlesung = vorlesung;
}

Why do I have "private access" error even if I didn't return any field?

I am learning OOP in Java. When finishing coding and compiling it, the compiler shows that this Manager class has private access to the Photographer class. I've been working on for a whole night, but I still cannot find the problem. Anyone could tell me how to fix it?
public class Manager
{
private ArrayList<Assignment> toDoList;
private ArrayList<Photographer> employees;
public Manager()
{
this.toDoList = new ArrayList<Assignment>();
this.employees = new ArrayList<Photographer>();
}
public void hire(String photographer)
{
employees.add(new Photographer(photographer));
}
public void giveOutAssignments()
{
int maxId;
if(toDoList.size()!=0 && employees.size()!=0){
for(Photographer p: employees){
maxId = 0;
//get highest priority
for(int i = 1; i<toDoList.size();i++){
//just check the unfinished assigns
if(!toDoList.get(i).getStatus()){
if(toDoList.get(i).getPriority()>toDoList.get(maxId).getPriority())
maxId = i;
}
}
//take the highest priority
Assignment currentAssign = toDoList.get(maxId);
//HERE IS THE PROBLEM
p.takePicture(currentAssign.getDescription());
//set it as finished
toDoList.get(maxId).setStatus();
}
}
}
}
Here is the Photographer class:
public class Photographer
{
private Map photos;
private String name;
public Photographer(String name)
{
photos = new HashMap(); // An important line. Must go in the constructor.
readPhotos(); // A very important line. this must go in the Photographer
// constructor so that the photographer will be able to take Pictures.
this.name = name;
}
private String takePicture(String description)
{
return photos.get(description);
}
private void readPhotos()
{
Pattern commentPattern = Pattern.compile("^//.*");
Pattern photoPattern = Pattern.compile("([a-zA-Z0-9\\.]+) (.*)");
try
{
Scanner in = new Scanner(new File("photos.txt"));
while (in.hasNextLine())
{
String line = in.nextLine();
Matcher commentMatcher = commentPattern.matcher(line);
Matcher photoMatcher = photoPattern.matcher(line);
if (commentMatcher.find())
{
// This line of the file is a comment. Ignore it.
}
else if (photoMatcher.find())
{
String fileName = photoMatcher.group(1);
String description = photoMatcher.group(2);
photos.put(description, fileName);
}
}
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
}
takePicture is declared private, it is inaccessible from any other context other than Photographer...
private String getDescription() {
change it to public...
public String getDescription() {
Take a look at Controlling Access to Members of a Class for more details
ps-
I also had an issue with the return type of takePicture in Photographer...
private String takePicture(String description)
{
return photos.get(description);
}
And had to change to something more like...
public String takePicture(String description) {
return (String)photos.get(description);
}

Why do i recieve "[Ljava.lang.Integer;#72608760" when i attempt to print out an Integer array [duplicate]

This question already has answers here:
Why does println(array) have strange output? ("[Ljava.lang.String;#3e25a5") [duplicate]
(6 answers)
Closed 9 years ago.
Here is the code.
public class PokerGame
{
public static void main(String args[])
{
Scanner kb=new Scanner(System.in);
Scanner nkb=new Scanner(System.in);
Random r=new Random();
Double jackpot;
System.out.println("Enter the number of people playing");
int players=nkb.nextInt();
List<PokerPlayer> player;
PokerPlayer[] Playersstorage=new PokerPlayer[players];
List<String> Names=new ArrayList<String>();
List<Double> payin=new ArrayList<Double>();
List<Integer> deck;
player=new ArrayList<PokerPlayer>();
Boolean playersinit=true;
while(playersinit==true)
{
for(int x=0;x<players;x++)
{
System.out.println("Enter your name please, and then your pay in amount");
Names.add(kb.nextLine().toLowerCase());
payin.add(nkb.nextDouble());
}
System.out.print("\f");
playersinit=false;
}
Boolean playing=true;
while(playing==true)
{
deck=new ArrayList<Integer>(52);
final int decksize=52;
Boolean deckshuffled=true;
while(deckshuffled==true)
{
while(deck.size()<decksize)
{
Boolean selectRandom=true;
Integer currentRandom=0;
while(selectRandom==true)
{
Boolean comparecard=true;
currentRandom=r.nextInt(52)+1;
while(comparecard==true)
{
if(deck.contains(currentRandom))
{
comparecard=false;
}
else
{
selectRandom=false;
comparecard=false;
}
}
}
deck.add(currentRandom);
if(deck.size()==decksize)
{
deckshuffled=false;
}
}
}
boolean card_distributor=true;
while(card_distributor==true)
{
boolean playerstarter=true;
Integer o=deck.size()-1;
Integer pinit=0;
Integer ps=1;
while(playerstarter==true)
{
int[] mycards= new int[2];
mycards[0]=deck.get(o);
deck.remove(deck.size()-1);
int newdecksize=deck.size();
Playersstorage[pinit]=new PokerPlayer(Names.get(pinit),payin.get(pinit),mycards);
player.add(Playersstorage[pinit]);
pinit++;
o=deck.size()-1;
if(ps==players)
{
playerstarter=false;
playing=false;
card_distributor=false;
}
ps++;
}
}
Boolean playingCards=true;
List<Integer> dealerHand=new ArrayList<Integer>();
Integer dealing=deck.size()-1;
jackpot=0.00;
while(playingCards==true)
{
/*for(int x=0;x<3;x++)
{
dealerHand.add(deck.get(dealing));
deck.remove(dealing);
dealing=deck.size()-1;
}*/
try
{
Thread.sleep(1000/1);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println("What is your name?");
String name=kb.nextLine().toLowerCase();
boolean betting=true;
while(betting==true)
{
System.out.println("Enter your bet");
Integer bet=nkb.nextInt();
int indexofbet=Names.indexOf(name);
if(bet>player.get(indexofbet).getMoney())
{
System.out.println("You can not bet that much without selling your first born childs soul, would you like to do this?");
String sellchild=kb.nextLine();
if(sellchild.equalsIgnoreCase("yes"))
{
jackpot+=bet;
betting=false;
}
else
{
betting=true;
}
}
else
{
jackpot+=bet;
betting=false;
}
}
System.out.println(jackpot);
try
{
Thread.sleep(1000/1);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println("\f");
if(Names.contains(name))
{
Integer index=Names.indexOf(name);
System.out.println(player.get(index).getCards());
Boolean notfinished=true;
while(notfinished==true)
{
try
{
Thread.sleep(1000/1);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Are you finished looking at your cards "+name+"?");
String done=kb.nextLine();
if(done.equalsIgnoreCase("Yes"))
{
System.out.println("\f");
notfinished=false;
}
}
}
}
List<Integer> gameEnd=new ArrayList<Integer>();
List<Integer> comparison=new ArrayList<Integer>();
Boolean checkplayersscore=true;
while(checkplayersscore==true)
{
for(Integer x=0;x<players;x++)
{
if(player.get(x).getMoney()==0.00)
{
System.out.println(player.get(x).getMoney()+player.get(x).getName());
gameEnd.add(1);
}
else
{
System.out.println(player.get(x).getMoney()+player.get(x).getName());
gameEnd.add(2);
}
comparison.add(2);
}
Boolean continuecheck=true;
int checkover=1;
while(continuecheck==true)
{
if(gameEnd.contains(1))
{
Integer remove=gameEnd.indexOf(1);
gameEnd.remove(remove);
comparison.remove(remove);
Names.remove(remove);
payin.remove(remove);
player.remove(remove);
Playersstorage[remove]=null;
}
if(gameEnd.containsAll(comparison))
{
continuecheck=false;
checkplayersscore=false;
playing=false;
}
if(checkover==players)
{
continuecheck=false;
checkplayersscore=false;
}
if(player.size()==0)
{
continuecheck=false;
checkplayersscore=false;
playing=false;
}
checkover++;
}
}
}
}
}
public class PokerPlayer
{
private String name;
private Double money;
private Integer[] cards;
public PokerPlayer(String na,Double n,int[] card)
{
name = na;
money=n+0.00;
cards=new Integer[card.length];
cards[0]=card[0];
cards[1]=null;
}
public Integer BJScore(List<Integer> mycards)
{
/*unfinished code*/
}
public Integer[] getCards()
{
return cards;
}
public void setCards(int card)
{
for(int x=0;x<cards.length;x++)
if(cards[x]==null)
cards[1]=card;
}
public void setMoney(Double d)
{
money-=(d+0.00);
}
public Double getMoney()
{
return money;
}
public String getName()
{
return name;
}
}
I am attempting to create a blackjack game for my AP java class, when i go to obtain and print out the cards that you have been given, which is currently only 1 card stored in the 0 index of the array, and a null in the second index(set in the constructor class), it sends me [Ljava.lang.Integer;#72608760 or some other numeral variation(I am assuming that it is varying due to changing cards each time it is called). Does anyone know the reason it is printing this out instead of the actual values that have been stored in the Integer array?
That's because array objects don't have a meaningful toString() method, they just use the default toString() in Object, which prints the class name and a memory address. Better use this for printing arrays:
System.out.println(Arrays.toString(array));
Here's a link to the documentation, and don't forget to import the Arrays class, it's in the package java.util.
Arrays are objects too in Java, but they don't override Object's toString() method. The output that you see is from Object's toString() method. Quoting from Object's javadocs:
The toString method for class Object returns a string consisting of
the name of the class of which the object is an instance, the at-sign
character `#', and the unsigned hexadecimal representation of the hash
code of the object. In other words, this method returns a string equal
to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
The getClass().getName() part is responsible for the [Ljava.lang.Integer part, and the hashCode, which for objects is usually based on the memory address, is responsible for the changing numerical variation at the end.
To get the desired output, you can use Arrays.toString() passing in your array.

Java Question Linked List objects

I have the following piece of code :
Essentially the number of methods should remain the same as in the code and I need to extract a string from an element of the linkedlist of Objects of type emp_struct.. How do I do it?
import java.util.*;
import java.io.*;
class a1 {
static LinkedList l1;
private emp_struct input() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
emp_struct obj = new emp_struct();
obj.emp_id = br.readLine();
obj.name = br.readLine();
obj.salary = Double.parseDouble(br.readLine());
obj.dept = br.readLine();
try{
search(obj);
}catch(Exception e){
System.out.println(e);
obj = input();
}
return obj;
}
boolean search(emp_struct obj)
{
int lastIndex = l1.lastIndexOf(l1);
int begIndex = 0;
for(begIndex =0;begIndex<lastIndex;begIndex++)
{
Object chkCase = l1.get(begIndex);
String chk = chkCase.getEmpID();
if(chk.equals(obj.emp_id));
throw new DuplicateEntryException("Duplicate entry found");
}
return true;
}
public static void main(String args[]) throws IOException
{
l1 = new LinkedList();
}
}
class DuplicateEntryException extends Exception {
String detail;
DuplicateEntryException(String a)
{
detail = a;
}
public String toString()
{
return "User Defined Exception : "+detail;
}
}
class emp_struct {
public String emp_id;
public String name;
public double salary;
public String dept;
public String getEmpID()
{
return emp_id;
}
public String toString()
{
return emp_id+"\t"+name+"\t"+salary+"\t"+dept;
}
}
In your search method, if you find the value, you're throwing an exception. If you don't find the value, you return true. This doesn't seem like the best approach.
If you find the value, shouldn't you return true, then if it makes it through the array without finding it, shouldn't you return false?
This line
Object chkCase = l1.get(begIndex);
should be
emp_struct chkCase = (emp_struct)l1.get(begIndex);
among other things...

Categories

Resources