Java array of an object variable change - java

I am new to Java. This is giving out an error.
private class applicantInfo {
int Id;
double quality;
}
private class allApplicants {
applicantInfo[] applicantArr = new applicantInfo[20];
}
public void newGame {
allApplicants applicants = new allApplicants();
applicants.applicantArr[0].Id = 5;
}
I am getting an error at the point of applicants.applicantArr[0].Id = 5;.
All I want to do is similar to this in C:
typedef struct _applicantInfo{
int Id;
double quality;
} applicantInfo;
typedef struct _allApplicants {
applicantInfo applicantArr[20];
} allApplicants;
int main () {
allApplicants applicants;
applicants.applicantArr[0].Id = 5;
}
How can I do that in Java?

The difference between Java and C arrays is that C initialises all the values in the Array, whilst Java sets them to null. So when you call
applicants.applicantArr[0].Id = 5;
You will get a NullPointerException, as applicants.applicantArr[0] is null.
You need to create a new applicantInfo and put it into the array before accessing it:
allApplicants applicants = new allApplicants();
applicants.applicantArr[0] = new applicantInfo();
applicants.applicantArr[0].Id = 5;

you need to do this in your newGame():
applicantInfo item = new applicantInfo();//first create a applicantInfo object
item.Id= 5;//set the object properties
applicants.applicantArr[0]= item;//assign the object to the array
this is because Arrays work in a different way in Java than those in C. Take a look at this
and also here is a tutorial to get you started with.

I would suggest a high-level structure for your code with comments and TODOs, you can fill in the details. And the last part, where I suggest the structure for newGame method, will help you get rid of the error you are getting.
The structure for ApplicantInfo class:
public class ApplicantInfo {
private int ID;
private double quality;
// Constructor to create an instance with the specified ID value
public ApplicantInfo(int id){
// TODO: Initialize the value for ID field
}
// Method to get the value for ID
public int getID(){
// TODO: return value of ID field
}
// Method to set the value for ID
public void setID(int id){
// TODO: set the value for ID field
}
// Getter and setter methods for "quality"
// on the lines of the above methods
}
The structure for AllApplicants class:
public class AllApplicants {
private ApplicantInfo[] applicantArr = new ApplicantInfo[20];
// Method to get the applicant info at a given index
public ApplicantInfo getApplicant(int index){
// TODO: Get the applicant from the array present at the specified index
}
// Method to add an applicant info at a given index
public boolean addApplicant(ApplicantInfo applicant, int index){
// TODO: Try to add the specified applicant to the array at the specified index
// Return true to indicate that the applicant was successfully added,
// Return false to indicate that an applicant is already present at the specified index
}
}
As this is just a skeleton to
The structure for newGame method:
public void newGame {
AllApplicants applicants = new AllApplicants();
// In order to achieve doing "applicants.applicantArr[0].Id = 5;", you
// need to do the following.
// Create a new applicant info with ID as 5
ApplicantInfo applicant = new ApplicantInfo(5);
// Add the applicant to the applicant array at index 0
applicants.addApplicant(applicant, 0);
}
In addition to reading about array, as mentioned by #codeman, you may also want to take a look at Java Naming Convention

Related

Why we can use methods of ArrayList without creating new ArrayList object?

We have to create a object of any class to use their funtionalities unless those are static functionalities. But why we dont need to create a ArrayList object to use its methods like add, contains etc..
ArrayList<Egg> myList = new ArrayList<Egg>();
myList.add(a);
According to my understanding, myList is just variable which holds ArrayList object's reference of type ArrayList class. So again how can we write following without passing object to myList.
ArrayList<Egg> myList;
myList.add(a);
Complete code:
import java.util.ArrayList;
public class DotCom {
private ArrayList<String> locationCells;
public void setLocationCells(ArrayList<String> loc)
{
locationCells = loc;
}
public String checkYourself(String userInput)
{
String result = "miss";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
}
else
{
result = "hit";
}
}
return result;
}
//TODO: all the following code was added and should have been included in the book
private String name;
public void setName(String string) {
name = string;
}
}
PS
I am referring heads first java book.
The ArrayList reference is being set in the setter method:
public void setLocationCells(ArrayList<String> loc)
{
locationCells = loc;
}
If this method is not called, and the reference not set before trying to use the ArrayList, then the code will throw a NullPointerException.
Side note: This does not look to be safe code, since it can be easily run incorrectly and so a NPE is easy to create. Better perhaps to set the ArrayList (List is even better) in a constructor.

JAVA how to check array parameter

I have 2 classes. one is named "shipment", the other is called "Inventory"
inside the shipment, there are some variables as below.
public class Shipment
{
private int trackingCode;
private int priority;
private double shippingPrice;
private double weight;
private String originCity;
private String destCity;
private String trackingPage;
and I create the "Inventory" as below
public class Inventory
{
private ArrayList<Shipment> packages;
public Inventory(Shipment[] listOfPackage)
{
if(listOfPackage == null){
throw new IllegalArgumentException("List of Packages cannot be null.");
}
packages = new ArrayList<Shipment>(Arrays.asList(listOfPackage));
}
Now my question is how do I create a method to add a new package to the ArrayList, and also duplicate tracking code is not allowed need to throw an exception.
public ArrayList<Package> addPackage()
I'm very confusing how to do the duplicate tracking code check because it's one of the Shipment[] array element
You can use the this keyword to refer to your private member variables and still keep a similar naming convention for parameters passed into your constructor or functions. It makes your code much more understandable to others and to yourself =). Having two separate naming conventions for everything you pass into a class can get very confusing.
I have added a main function to demonstrate how you would effectively operate on these classes.
public class Application {
public static void main(String[] args) {
// define some unique shipments
Shipment a = new Shipment(1,1, 10.0, 20.3, "Denver", "Seattle", "xyz");
Shipment b = new Shipment(2,9, 45.88, 130.1, "Denver", "Los Angeles", "xyz");
Shipment c = new Shipment(3,3, 14.67, 6.8, "Houston", "Dallas", "xyz");
Shipment d = new Shipment(1,4, 12.99, 2.3, "New York", "London", "xyz");
// populate your inventory with an array of initial shipments "a", "b", and "c"
Shipment[] initialShipments = new Shipment[] { a, b, c };
Inventory inventory = new Inventory(initialShipments);
// print the inventory before adding the new shipment
System.out.println(inventory.toString());
// add shipment "d" to your inventory with the new method
try {
inventory.addShipment(d);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
// print the inventory after adding the new shipment
System.out.println(inventory.toString());
}
}
For your Inventory:
public class Inventory {
private ArrayList<Shipment> shipments;
public Inventory(Shipment[] shipments) {
if(shipments == null) {
throw new IllegalArgumentException("List of shipments cannot be null.");
}
this.shipments = new ArrayList<>(Arrays.asList(shipments));
}
public void addShipment(Shipment shipment) throws Exception {
Optional<Shipment> duplicateShipment = shipments
.stream()
.filter(otherShipment -> otherShipment.getTrackingCode() == shipment.getTrackingCode())
.findAny();
if(duplicateShipment.isPresent()) {
String errorMessage = MessageFormat.format(
"A shipment with tracking code {0} already exists in this inventory.",
shipment.getTrackingCode()
);
throw new Exception(errorMessage);
}
else {
this.shipments.add(shipment);
}
}
#Override
public String toString() {
return "Inventory{" +
"shipments=" + shipments +
'}';
}
}
In order to check for duplicate tracking codes, you must make a stream of your existing shipments so that you can look for any tracking code in those shipments that match the one you are trying to add.
There are many ways to accomplish this in theory, but I did it by making a stream of your shipments so I could make a filter that looked for any shipment tracking code equal to the one you are adding.
The findAny at the end of this stream just returns an Optional which means that it could potentially return something or not.
With the Optional type, you can test if it found a duplicate by using the isPresent() function. If the duplicate is present, you can throw an exception, as needed.
Here I just made the function throw up the Exception, but you could handle it here in the function and just log that you tried to add the same shipment. In real code, you wouldn't want your code to break because you tried to add a duplicate shipment. You would just want to stop it from happening and move on!
For your Shipment:
public class Shipment {
private int trackingCode;
private int priority;
private double shippingPrice;
private double weight;
private String originCity;
private String destCity;
private String trackingPage;
public Shipment(int trackingCode, int priority, double shippingPrice, double weight, String originCity, String destCity, String trackingPage) {
this.trackingCode = trackingCode;
this.priority = priority;
this.shippingPrice = shippingPrice;
this.weight = weight;
this.originCity = originCity;
this.destCity = destCity;
this.trackingPage = trackingPage;
}
public int getTrackingCode() {
return trackingCode;
}
}
You need to add a 'getter' to the Shipment class so that you can access the tracking code outside of this class; otherwise, it will remain private, and you won't be able to make comparisons outside of this class where you need to check for duplicate tracking codes.

Create an object and put in an array

I want to create just an object,i am not sure if i am creating and it is right.My example ,lets say i have 2 class(Userinput and paper).0fcourse there is and the main.In this example No inherit (just 2 simple class).Am i create an object right?How i put in it in an array or in the same array?
package exercise;
public class Exercise{
static int N; //from keyboard .I have a class userinput.It doesnt need to write it here ,i have in the other class the problem
public static void main(String[] args) { // main class
Paper[] pin = new Paper[N]; //i create an array
Paper.setpencil(3); // i wrote the 3 .In this way i create 3 pencil?
Paper.getpencil(3);
Paper.setsomething(4); // i wrote the 4 .I create 4 ?
Paper.getsomething(4);
} }
public class Paper{ //in this class i am confused
public Paper(){} //default constructor
private int pencil;
private String something;
public int getpencil(){
return pencil;
}
public void setpencil(){
pencil=UserInput.getInteger():
}
public int getsomething(){
return something;
}
public void setsomething(){
something=UserInput.setInteger();
}
}
with this statement:
Paper[] pin = new Paper[N];
you create an array of object of class Paper.
You must also create an object for each array element like:
for (int i=0; i < N, i++)
{
pin[i] = new Paper();
}
And next you should refer to an element (e.g. first element that with index 0) of the array in this way:
pin[0].setpencil(3);

Printing address instead of array elements? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
So in my code, I made a class named Pet, that would have both a default constructor and a non-default constructor that passes in String name, and int age of the pet.
public class Pet
{
// instance variables
private int age;
private String name;
/**
* Constructor for objects of class Pet
*/
public Pet()
{
// initialise instance variables
age = 0;
name = "somePet";
}
public Pet(int age, String name)
{
this.age = age;
this.name = name;
}
}
Then I created a class named petArray that would add to the array and print out the array...
public class PetArray
{
// instance variables
private Pet [] petArray;
/**
* Constructor for objects of class PetArray
*/
public PetArray()
{
// initialise instance variables
petArray = new Pet[5];
}
public void addPets()
{
// put your code here
Pet myPet = new Pet(4, "Spots");
petArray[0] = (myPet);
petArray[1] = new Pet(2, "Lucky");
petArray[2] = new Pet(7, "Joe");
}
public void printPets()
{
for (int i = 0; i < petArray.length; i++)
{
System.out.println(petArray[i]);
}
}
}
But then, I get this in the terminal window when trying to print it out...
Pet#13255e3c
Pet#171ac880
Pet#52185407
null
null
You forgot to override toString() method inherited from Object.
In this case you can use something like this:
#Override
public String toString() {
return (name + age);
}
Java compiler just does not know how to print it, you have to inform it :)
In your addPets() method you are only adding 3 objects to your petArray while there are 2 more spaces you need to fill as you declared that array to be a length of 5.
You could change the length of your array down to 3 or you could add 2 more objects, that should fix your problem.
And as stated above, adding the toString method will get rid of the addressing issues.
class Pet {
...
#Override
public String toString(){
// the string passed from here will be shown in console
}
}
Your output is fine according to your code. You have to override toString() method to print as per your requirement. Add this may be it will help.
#override
public string toString(){
return "your required string"; // i.e : name or name+age
}

Should I create a method or variable for the table given below

I have an assignment which says that I need to create an queue class with instruction messages on it.
and instruction message is formed of following properties
-----------
>InstructionType integer
> ProductCode integer
> Quantity integer
> UOM byte
--------------------------------
Can I declare all the above given properties as variables and then pass it as a parameter in a function created for instruction message and place it in the instruction queue class. Can anyone give me a sample code for proceeding with this..and let me know if I think right or any other methodologies. Can be done? please help.
Can anyone suggest ,If am right.Can i use like this:
public class instructionqueue
{
LinkedList queue = new LinkedList()
/* how to add,retreive and delete the instructionmessage from the queue class*/
}
where insturctionmessage is a class
public class Instructionmessage
{
public int Instructiontype;
public Integer Productcode;
public Integer quantity;
public byte[] UOM = new byte[256];
public Integer Timestamp;
/*method to set and get the instruction type for the messages*/
public int getInstructiontype()
{
return Instructiontype;
}
public void setInstructiontype(int newInstructtype)
{
Instructiontype = newInstructtype;
}
/*method to set and get the product code for the messages*/
public int getProductcode()
{
return Productcode;
}
public void setProductCode(int newproductcode)
{
Productcode = newproductcode;
}
/*method to set and get the quantity for the messages*/
public int getquantity()
{
return quantity;
}
public void setquantity(int newquantity)
{
quantity = newquantity;
}
/*method to set and get the Timestamp for the messages*/
public int getTimestamp ()
{
return Timestamp;
}
public void setTimestamp(int newTimestamp)
{
Timestamp = newTimestamp;
}
/*method to set and get the UOM for the messages*/
public byte[] getUOM()
{
return UOM;
}
public void setUOM(byte[] newUOM)
{
UOM = newUOM;
}
}
Since the instruction message consists of 4 fields, you could create an Instruction class to encapsulate them. Then, for the queue you could use a list, and populate it with Instructions. For example, instantiate
LinkedList<Instruction> queue = new LinkedList<Instruction>();
You could then use queue.getFirst() and queue.addLast(...) to manipulate the queue's contents.
Create a POJO java class with all your variables. The create getters and setters for all variables. This will help you to set and get data using the methods.
Now create a Queue object in your main class and add(Object) method to add it in the queue.
Queue<String> sampleQueue = new LinkedList<String>();
sampleQueue.add("Joseph");
sampleQueue.add("Madhonna");
Note: Queue is an interface, so you cannot instantiate the object.
Possible exceptions can be thrown when you use this method. Refer this link for more details http://docs.oracle.com/javase/6/docs/api/java/util/Queue.html#add(E)
IllegalStateException - if the element cannot be added at this time
due to capacity restrictions List item
ClassCastException - if the class of
the specified element prevents it from being added to this queue
NullPointerException - if the specified element is null and this
queue does not permit null elements
IllegalArgumentException - if some property of this element prevents it from being added to this queue

Categories