Making an array out of a custom class? - java

import java.io.*;
public class workPoS {
/**
* #param args
*/
public static void main(String[] args) {
dataList[] some_list = new dataList[10];
for (int x = 0; x < some_list.length; x++) {
some_list[x].firstName = "John";
some_list[x].middleName = "Jacob";
some_list[x].lastName = "Jingle-Heimer-Schmidt";
some_list[x].age = 101;
}
for (int x = 0; x < some_list.length; x++) {
System.out.println(some_list[x].firstName + " "
+ some_list[x].middleName + " " + some_list[x].lastName
+ " Age: " + some_list[x].age);
}
}
public class dataList {
String firstName, middleName, lastName;
int age;
public dataList() {
firstName = "";
middleName = "";
lastName = "";
age = 0;
}
}
}
ERROR: Exception in thread "main" java.lang.NullPointerException
at workPoS.main(workPoS.java:12)
This is line 12:
some_list[x].firstName = "John";
It seems that I am able to access some_list[x], but as soon as I specify a constructor, some_list[x].firstName, the result is a null value.
Am I simply referencing the constructor value incorrectly?
If so, what is the correct way to do so?
Thanks guys!

Look here:
dataList[] some_list = new dataList[10];
for (int x = 0; x < some_list.length; x++) {
some_list[x].firstName = "John";
You've created the array - but all the elements will be null references. You talk about "referencing the constructor value incorrectly" - you're not calling the constructor at all. You should have:
for (int x = 0; x < some_list.length; x++) {
some_list[x] = new dataList();
some_list[x].firstName = "John";
See the Java Tutorial for Arrays for more information.
(You should also fix your names to follow Java naming conventions, and make your fields private, but that's a different matter...)

If you are using both the classes in the same .java file, the try this code
import java.io.*;
public class workPoS {
public workPoS() {
super();
}
/**
* #param args
*/
public static void main(String[] args) {
workPoS wp = new workPoS();
dataList[] some_list = new dataList[10];
for (int x = 0; x < some_list.length; x++) {
some_list[x] = wp.new dataList();
some_list[x].firstName = "John";
some_list[x].middleName = "Jacob";
some_list[x].lastName = "Jingle-Heimer-Schmidt";
some_list[x].age = 101;
}
for (int x = 0; x < some_list.length; x++) {
System.out.println(some_list[x].firstName + " "
+ some_list[x].middleName + " " + some_list[x].lastName
+ " Age: " + some_list[x].age);
}
}
public class dataList {
String firstName, middleName, lastName;
int age;
public dataList() {
firstName = "";
middleName = "";
lastName = "";
age = 0;
}
}
}

Related

How to use array of objects in this context?

Assuming that the array is populated with 20 shipments, calculate the total cost of local shipments in the array.
I tried to create a for loop and then call out the method calcCost() and += it to the variable local so it would save the values I guess
I'm pretty sure the way I wrote the code is wrong so if someone could help me with it that would be great!
package question;
public class TestShipment {
public static void main(String[] args) {
Shipment r1 = new Shipment(
new Parcel("scientific calculator " , 250),
new Address("Dubai","05512345678"),
new Address("Dubai","0505432123"),
"Salim"
);
System.out.println(r1);
Shipment[] arr = new Shipment[100];
arr[5] = r1;
Shipment[] a = new Shipment[20];
double local = 0;
for (int i = 0; i < a.length; i++) {
if (a[i].isLocalShipment()) {
System.out.println(a[i].calcCost());
}
}
}
}
public class Shipment {
public Parcel item;
private Address fromAddress;
private Address toAddress;
public String senderName;
public Shipment(Parcel i, Address f, Address t, String name) {
item = i;
fromAddress = f;
toAddress = t;
senderName = name;
}
//setter
public void setFromAddress(String c, String p) {
c = fromAddress.getCity();
p = fromAddress.getPhone();
}
public boolean isLocalShipment() {
boolean v = false;
if (fromAddress.getCity() == toAddress.getCity()) {
v = true;
} else {
v = false;
}
return v;
}
public double calcCost() {
double cost = 0;
if (fromAddress.getCity() == toAddress.getCity()) {
cost = 5;
} else {
cost = 15;
}
if(item.weight > 0 && item.weight <= 200) {
cost += 5.5;
}
if(item.weight > 200) {
cost += 10.5;
}
return cost = cost * (1 + 0.5); //fix the tax
}
public String toString() {
return "From: " + senderName + "\nTo: " + toAddress
+ "\nParcel: " + item.desc+item.weight + "\ncost: " + calcCost();
}
}

Java not outputting or requesting keyboard input

I am having trouble getting my java code to properly output the required results. Not to mention that my System.out.Println isn't prompting for input. All my code is good with no errors. However it just doesn't seem to output anything or request an input.
//Author Adam Duffy
package test1;
import java.util.Scanner;
public class Employee {
public static void main(String [ ] args){}
public String DEF_EMP_NUM = "NO_EMP_NUM";
public double DEF_RATE_PER_HOUR = 20.0;
public double DEF_OVER_TIME_RATE = 40.0;
public double DEF_RATE_HOURS_PER_WEEK = 1.5;
private String empNum;
private double ratePerHour;
private double baseHrsPerWeek;
private double overTimeRate;
// no arg constructor setting width and length to default of 1
public Employee() {
empNum = DEF_EMP_NUM;
ratePerHour = DEF_RATE_PER_HOUR;
baseHrsPerWeek = DEF_RATE_HOURS_PER_WEEK;
overTimeRate = DEF_OVER_TIME_RATE;
}
// all arg constructor
public Employee(String empNum, float ratePerHour, float baseHrsPerWeek, int overTimeRate) {
this.empNum = empNum;
this.ratePerHour = ratePerHour;
this.baseHrsPerWeek = baseHrsPerWeek;
this.overTimeRate = overTimeRate;
}
//setters
public void setempNum(String empNum) {
this.empNum = empNum;
}
public String getempNum() {
return this.empNum;
}
//methods
public double getratePerHour() {
return ratePerHour;
}
public void setratePerHour(float ratePerHour) {
this.ratePerHour = ratePerHour;
}
public double getoverTimeRate() {
return overTimeRate;
}
public int setoverTimeRate(int overTimeRate) {
this.overTimeRate = overTimeRate;
return overTimeRate;
}
public double getbaseHrsPerWeek() {
return baseHrsPerWeek;
}
public void setbaseHrsPerWeek(float baseHrsPerWeek) {
this.baseHrsPerWeek = baseHrsPerWeek;
}
#Override
public String toString() {
return super.toString()
+ "\n["
+ "\nbaseHrsPerWeek = " + baseHrsPerWeek
+ "\noverTimeRate = " + overTimeRate
+ "\nratePerHour = " + ratePerHour
+ "\nempNum = " + empNum
+ "\n]";
}
public double calcWeeksPay(int hours) {
return this.ratePerHour * this.baseHrsPerWeek;
/*#param hours
#return
*/
}
{
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
}
}
I just can't seem to get it to work. I'm sure I'm missing something obvious. If I could get some advice, I would be very appreciative.
Updated peice of code , which will accept and print the number on console.
public class Employee {
public static void main(String [ ] args){
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
}
public String DEF_EMP_NUM = "NO_EMP_NUM";
public double DEF_RATE_PER_HOUR = 20.0;
public double DEF_OVER_TIME_RATE = 40.0;
public double DEF_RATE_HOURS_PER_WEEK = 1.5;
private String empNum;
private double ratePerHour;
private double baseHrsPerWeek;
private double overTimeRate;
// no arg constructor setting width and length to default of 1
public Employee() {
empNum = DEF_EMP_NUM;
ratePerHour = DEF_RATE_PER_HOUR;
baseHrsPerWeek = DEF_RATE_HOURS_PER_WEEK;
overTimeRate = DEF_OVER_TIME_RATE;
}
// all arg constructor
public Employee(String empNum, float ratePerHour, float baseHrsPerWeek, int overTimeRate) {
this.empNum = empNum;
this.ratePerHour = ratePerHour;
this.baseHrsPerWeek = baseHrsPerWeek;
this.overTimeRate = overTimeRate;
}
//setters
public void setempNum(String empNum) {
this.empNum = empNum;
}
public String getempNum() {
return this.empNum;
}
//methods
public double getratePerHour() {
return ratePerHour;
}
public void setratePerHour(float ratePerHour) {
this.ratePerHour = ratePerHour;
}
public double getoverTimeRate() {
return overTimeRate;
}
public int setoverTimeRate(int overTimeRate) {
this.overTimeRate = overTimeRate;
return overTimeRate;
}
public double getbaseHrsPerWeek() {
return baseHrsPerWeek;
}
public void setbaseHrsPerWeek(float baseHrsPerWeek) {
this.baseHrsPerWeek = baseHrsPerWeek;
}
#Override
public String toString() {
return super.toString()
+ "\n["
+ "\nbaseHrsPerWeek = " + baseHrsPerWeek
+ "\noverTimeRate = " + overTimeRate
+ "\nratePerHour = " + ratePerHour
+ "\nempNum = " + empNum
+ "\n]";
}
public double calcWeeksPay(int hours) {
return this.ratePerHour * this.baseHrsPerWeek;
/*#param hours
#return
*/
}
}
Problem was that you were not having anything in the psvm method and below piece of code
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
Which takes the input and print it on console was not having any calling code. it was just a inside the block of code. i just moved it inside the main method and it worked.

How to give variable of object-2 the same value as a variable in object-1?

Language:
Java.
Aim:
give variable name from object rooms[] (class: Room) the same value as variable nameGuest from object guest1 (class: Guest).
problem:
this doesn't work
void printRooms(){
for(int i = 0; i < rooms.length; i++){
rooms[i].roomNr = ""+(i+1);
for(int j = 0; j < 2; j++){
a = guest1.getName();
rooms[i].name = a;
}//end for
}//end for
}//end void
Reviewing:
I've tried rooms[i].name = guest1.nameGuest. That did not work. Making a method getName to return nameGuest didn't work either. Same goes for making a pit-stop variable a to store the value.
I'm new to inter-class coding and am currently trying to read more about how to do it on https://docs.oracle.com/javase/tutorial/java/javaOO/ and http://www.tutorialspoint.com/java/java_object_classes.htm But it's not working out.
Question:
How do you give object2.variable value to object1.variable
In this case, hotel must have a method printRooms that gives room[i] a number and the name(s) of the guest(s).
Here's my full code:
public class Hotel2 {
Guest[] guest;
Room[] rooms;
String a;
void execute() {
rooms = new Room[10];
Guest guest1 = new Guest("Alain");
Guest guest2 = new Guest("Jantje");
for (int i = 0; i < 9; i++) {
rooms[i] = new Room(guest1);
}
//2 guests in 1 room
rooms[9] = new Room(new Guest[]{guest1, guest2});
System.out.println(Arrays.toString(rooms));
printRooms();
}
void printRooms() {
for (int i = 0; i < rooms.length; i++) {
rooms[i].roomNr = "" + (i + 1);
for (int j = 0; j < 2; j++) {
a = guest1.getName();
rooms[i].name = a;
}//end for
}//end for
}//end void
public static void main(String[] args) {
(new Hotel2()).execute();
}
}
class Room {
Guest[] guests;
String roomNr;
String name;
//1 guest constructor
Room(Guest g) {
guests = new Guest[1];
guests[0] = g;
}
//several guests constructor
Room(Guest[] g) {
guests = g;
}
}
class Guest {
String nameGuest;
Guest(String n) {
nameGuest = n;
System.out.println(nameGuest);
}
String getName() {
return nameGuest;
}
}
It's really hard to understand what you're asking.
Your problem seems to be with this code:
void printRooms() {
for (int i = 0; i < rooms.length; i++) {
rooms[i].roomNr = "" + (i + 1);
for (int j = 0; j < 2; j++) {
a = guest1.getName();
// ^^^^^^ Compiler error: cannot resolve symbol "guest1"
rooms[i].name = a;
}
}
}
Notice the comment ^^^^^ I put in there.
The code doesn't compile,
because the variable guest1 is undefined.
It's not defined inside the method,
and it's not defined as a field of the class.
If your intention is to overwrite each room's name using the first guest's name, this would be it:
void printRooms() {
for (int i = 0; i < rooms.length; i++) {
rooms[i].roomNr = "" + (i + 1);
rooms[i].name = room.guests[0].getName();
}
}
But this doesn't make sense for a method called printRooms,
as it prints nothing.
But I hope that based on this you'll figure out how to do what you really want to do.

java how to execute method

I have created a class Hotel defined as follows:
import java.util.Random;
public class Hotel {
private Osoba[] tab = new Osoba[100];
public void zamelduj(Osoba os, int num) {
if (tab[num - 1] == null) {
System.out.println("Pokoj o numerze " + num + "jest zajety");
return;
}
tab[num - 1] = os;
}
public void wymelduj(int num) {
tab[num - 1] = null;
}
public void zamienOsoby(int num1, int num2) {
Osoba o = tab[num1 - 1];
tab[num1 - 1] = tab[num2 - 1];
tab[num2 - 1] = o;
}
public void znajdzWolnePokoje() {
for (int i = 0; i < 100; i++) {
if (tab[i] == null) System.out.println(i + 1);
}
}
public void przydzielPokoje50() {
for (int i = 0; i < 50; i++) {
Random r = new Random();
Osoba o = new Osoba();
int num = r.nextInt(100);
tab[num] = o;
}
}
public void wypisz() {
for (int i = 0; i < 100; i++) {
if (tab[i] == null) System.out.println("Pokoj nr. " + (i + 1) + " jest wolny");
else System.out.println("Pokoj nr. " + i + " jest zajety przez " + tab[i].imie + " " + tab[i].nazwisko);
}
}
public static void main(String[] args) {
Hotel h = new Hotel();
//h.przydzielPokoje50();
//h.wypisz();
h.zamelduj(null, 30);
}
}
I also have a class Osoba:
public class Osoba {
public String imie;
public String nazwisko;
Osoba() {
imie = null;
nazwisko = null;
}
Osoba(String imie, String nazwisko) {
this.imie = imie;
this.nazwisko = nazwisko;
}
}
I want to execute the method Zamelduj, which will assign a person (Osoba) to a cell in a table. However, every time I insert something other than null in the following it says that the first argument is not a capable parameter of the method.
h.zamelduj(null, 30);
What am I doing wrong?
I think your problem is that on the line " h.zamelduj(null, 30);" you need to create a new Osoba:
h.zamelduj(new Osoba("o.o", "._.!"), 30);
what happens is that the function is expecting a Osoba, if you give it another thing, it refuses. i hope it helps
You need to create an object of the class hotel (in your class from where you want to call the method type):
Hotel myObjectHotel = new Hotel();
And then you can call the method trough:
myHotelObject. zamelduj(give parameters here);
:)
Update:
Missed the real question. Just focused on the topic. I'm sorry. ;)

How to grab value from array list?

A briefing of the program: This program keeps track of people who have airline membership cards and how many points they collect each week. (week1, 2, 3, 4) The information is stored in the array, which then when needed, can be outputted by pressing the "listButton".
I know how to grab a value from the array and simply output it, but unsure how to do so with a loop. See problem area under "totalPointsButton"
public class AirlineCardsView extends FrameView {
class airline {
String lastName, firstName;
int week1, week2, week3, week4;
airline (int _week1, int _week2, int _week3, int _week4, String _lastName, String _firstName) {
week1 = _week1;
week2 = _week2;
week3 = _week3;
week4 = _week4;
lastName = _lastName;
firstName = _firstName;
}
}
/** Define the ArrayList */
ArrayList <airline> members = new ArrayList <airline>();
public AirlineCardsView(SingleFrameApplication app) {
//GUI stuff
}// </editor-fold>
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
String lastName, firstName;
int week1, week2, week3, week4;
week1 = Integer.parseInt(weekOneField.getText());
week2 = Integer.parseInt(weekTwoField.getText());
week3 = Integer.parseInt(weekThreeField.getText());
week4 = Integer.parseInt(weekFourField.getText());
lastName = lastNameField.getText();
firstName = firstNameField.getText();
airline c = new airline(week1, week2, week3, week4, firstName, lastName);
members.add(c);
}
private void listButtonActionPerformed(java.awt.event.ActionEvent evt) {
String temp = "";
for (int x=0; x<=members.size()-1; x++) {
temp = temp + members.get(x).firstName + " "
+ members.get(x).lastName + ": "
+ members.get(x).week1 + " "
+ members.get(x).week2 + " "
+ members.get(x).week3 + " "
+ members.get(x).week4 + "\n";
}
memberListTArea.setText(temp);
}
Here I'm unsure how to initialize the values week1, week2, week3, week4 (for int totalPoints) with the same values stored in the array for the corresponding member.
private void totalPointsButtonActionPerformed(java.awt.event.ActionEvent evt) {
int week1, week2, week3, week4;
String lastName, firstName;
String points = "";
for (int j = 0; j < members.size()-1; j++) {
//this line checks the inputted name to see if it matches any stored in array.
if (members.get(j).lastName.equals(lastNameField.getText())) {
int totalPoints = week1 + week2 + week3 + week4; //then adds total points
}
}
}
I hope I understood the question correctly....
firstly, this line has problem:
for (int j = 0; j < members.size()-1; j++) {
you should remove the -1 or use <=. otherwise you won't reach the last element.
the if (members.get(j).lastName.equals(lastNameField.getText())) may throw NPE. (members.get(j).lastName could be null) also the variables defined in this method (week1-4, and the lastname, firstname) don't make much sense.
you declare the int totalPoints in if block, which means, it won't be seen outside the if block. It is not big deal, if all your logic is in if block.
you could try:
Airline al = null;
int totalPoints;
for (int j = 0; j < members.size(); j++) {
al = members.get(j);
if (al.lastName.equals(lastNameField.getText())) {
totalPoints = al.week1 + al.week2 + al.week3 + al.week4;
}
}
even better:
int totalPoints;
for (Airline al:members) {
if (al.lastName.equals(lastNameField.getText())) {
totalPoints = al.week1 + al.week2 + al.week3 + al.week4;
}
}
to make the codes look better, you could consider add getter/setters in your Airline class. also add a method, int getTotalPoints() return the sum of 4 weeks. Then you don't have to sum it outside the class.
You should add get and set methods to your airline class. So when you store an object of airline in the arraylist you can get their values by using "members.get(j).week1, members.get(j).week2, etc"
For example create your airline class like this.
public class airline {
String lastName;
String firstName;
int week1;
int week2;
int week3;
int week4;
public airline (int week1, int week2, int week3, int week4, String lastName, String firstName) {
week1 = this.week1;
week2 = this.week2;
week3 = this.week3;
week4 = this.week4;
lastName = this.lastName;
firstName = this.firstName;
}
public int getWeek1(){
return week1;
}
public void setWeek1(int newWeek1){
week1 = newWeek1;
}
public int getWeek2(){
return week2;
}
public void setWeek2(int newWeek2){
week2 = newWeek2;
}
public int getWeek3(){
return week3;
}
public void setWeek3(int newWeek3){
week3 = newWeek3;
}
public int getWeek4(){
return week4;
}
public void setWeek4(int newWeek4){
week4 = newWeek4;
}
public String getFirstName(){
return firstName;
}
public void setFirstName(String newFirstName){
firstName = newFirstName;
}
public String getLastName(){
return lastName;
}
public void setLastName(String newLastName){
lastName = newLastName;
}
public String toString(){
return getWeek1() + " " + getWeek2() + " " + getWeek3() + " " + getWeek4() + getFirstName() + " " + getLastName();
}
}

Categories