I'm new to Java. Please help me understand Java.
I have trouble understanding some my teacher's code about "stacks."
The code bellow is for my class Person. My question is what does private Person next; mean? Why this variable such with class name ? What is this class doing?
public class Person {
private String _name, _address;
private int _id;
private Person next; // what is this mean and do
public Person(String a, String b, int c){
this._name = a;
this._address = b;
this._id = c;
}
public Person(){
}
public String getname(){
return this._name;
}
public String getaddress(){
return this._address;
}
public int getid(){
return this._id;
}
public person getnext(){
return this.next;
}
public void setname(String a){
this._name = a;
}
public void setaddress(String a){
this._address = a;
}
public void setid(int a){
this._id = a;
}
public void setnext(person a){
this.next = a;
}
#Override
public String toString(){
return "Person{"+ "Name = " + _name +", Address" + _address +", Id = " + _id +'}';
}
}
And this is my code for main class. In this main class I can't understand what private static Person HeadStack contains and what it will do. Why is HeadStack keyword always used in method "pop", "push", and "print"?
public class mainmahasisswa {
private static Person HeadStack; // what is this mean & do
public static void main(String[] args) {
push();
push();
push();
print();
pop();
print();
pop();
print();
push();
print();
}
private static Person setdata(){
person pr = new person();
String name, address;
int id;
name = JOptionPane.showInputDialog("Name : ");
address = JOptionPane.showInputDialog("Address : ");
id = Integer.parseInt(JOptionPane.showInputDialog("id : "));
pr.setname(name);
pr.setaddress(address);
pr.setid(id);
pr.setnext(null);
return pr;
}
private static void pop(){
if (HeadStack != null){
person aa ;
aa = HeadStack.getnext();
HeadStack = aa;
}
else{
System.out.println();
}
}
private static void push(){
person x = setdata();
if(HeadStack != null){
x.setnext(HeadStack);
HeadStack = x;
}
else{
HeadStack = x;
}
}
private static void print(){
if(HeadStack != null ){
person y = HeadStack;
while(y != null){
System.out.println(y.toString());
y = y.getnext();
}
System.out.println();
}
else{
System.out.println();
}
}
}
Think of it as a link in the chain private person next provides a link to the "next" person object in this chain or null if it does not exist.
private person next; // what is this mean and do
This a declaration that says next is a type of person, which is initially assigned null
This...
private static person HeadStack; // what is this mean & do
is simply a declaration that says HeadStack is type of person which is static, meaning that it doesn't rely on particular instance of any class to be accessed.
Take a look at Language Basics: Variables and Understanding Class Members
why this HeadStack keyword always used in method "pop","push","print"
The object represents the first link in the chain
Related
So I have code that looks like this:
public class CLASSNAME {
private String name;
private int age;
public METHODNAME(String testName, int testAge) {
//does something
}
public ANOTHERMETHOD() {
//does something else
}
}
I have testName and testAge declared in another class, but I need to access them in my fields so I can use them in other methods. Right now I can only access testAge and testName in the METHODNAME method.
Any help would be much appreciated :)
You should add getters and setters (also called accessors and mutators). For Example,
public class Example {
public Example(String name, int age) {
this.name = name;
this.age = age;
}
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Then you can modify (or retrieve) the value(s) from an instance of the class.
you can use inheritance here. Parent class have some method. You will extend child class to parent class. And you will get all in child class from parent class.
Parent class need to have getter/setter also.
There is a complete example: Follow this
// A class to display the attributes of the vehicle
class Vehicle {
String color;
private int speed;
private int size;
public int getSize() {
return size;
}
public int getSpeed() {
return speed;
}
public void setSize(int i) {
size = i;
}
public void setSpeed(int i) {
speed = i;
}
}
// A subclass which extends for vehicle
class Car extends Vehicle {
int CC;
int gears;
int color;
void attributescar() {
// Error due to access violation
// System.out.println("Speed of Car : " + speed);
// Error due to access violation
//System.out.println("Size of Car : " + size);
}
}
public class Test {
public static void main(String args[]) {
Car b1 = new Car();
// the subclass can inherit 'color' member of the superclass
b1.color = 500;
b1.setSpeed(200) ;
b1.setSize(22);
b1.CC = 1000;
b1.gears = 5;
// The subclass refers to the members of the superclass
System.out.println("Color of Car : " + b1.color);
System.out.println("Speed of Car : " + b1.getSpeed());
System.out.println("Size of Car : " + b1.getSize());
System.out.println("CC of Car : " + b1.CC);
System.out.println("No of gears of Car : " + b1.gears);
}
}
Resource Link: http://beginnersbook.com/2013/03/inheritance-in-java/
I am implemeting a circular queue in java which will accept objects (Employee) as entries. Now I have a method to edit the surname of the specific object, but somehow I cannot access the surname setter method found in the Employee class from the CQueue class even though I am importing all the required packages. Here is the code:
//PACKAGES IMPORTED
package linearstructures;
import dataobjects.*;
import linearnodes.*;
public class CQueue{
Node front, rear, temp;
boolean full = false;
String key;
public AnyClass searchKey(String key)
{
temp = rear.next; // first node
do
{
if (temp.obj.getKey().equals(key))
return temp.obj;
temp = temp.next;
} while (temp != rear.next);
return null;
}
public AnyClass editObject(String key){
int choice, newSeqNo;
double newPay;
boolean exit = false;
Employee etemp = new Employee(); //INCLUDED THIS AFTER EDIT
searchKey(key);
if(searchKey(key) != null){
temp.obj.getData();
System.out.println();
System.out.println("------------------------");
System.out.print("Enter new Salary: ");
newPay = sc.nextDouble();
System.out.println("------------------------");
System.out.println();
etemp.setPay(newPay); //INCLUDED THIS AFTER EDIT
else
System.out.println("NO OBJECT WAS FOUND!");
return null;
}
}
Employee class:
package dataobjects;
public class Employee extends AnyClass
{
public String surname;
public double pay;
public Employee(){}
public Employee(int seqNo, String surname, double pay)
{
super(seqNo);
this.surname = surname;
this.pay = pay;
}
public double getSalary()
{
return pay;
}
public void setPay(double newPay)
{
pay = newPay;
}
public String getData()
{
return super.getData() + ", Surname: " + surname + ", Pay: " + pay;
}
public String getKey()
{
return surname;
}
}
AnyClass class:
package dataobjects;
public class AnyClass
{
public int seqNo;
public AnyClass(){}
public AnyClass(int seqNo)
{
this.seqNo = seqNo;
}
public int getseqNo()
{
return seqNo;
}
public void setseqNo(int seqNo) {
this.seqNo = seqNo;
}
public String getData()
{
return "Sequential Number - " + seqNo;
}
public String getKey()
{
return Integer.toString(seqNo);
}
public void edit(){}
}
Node Class
package linearnodes;
import dataobjects.*;
public class Node{
public AnyClass obj;
public Node next;
public Node(AnyClass obj){
next = null;
this.obj = obj;
}
}
Your editobject method could be something like this:
public AnyClass editObject(String key){
// ...
// Store your search result to avoid performing searchKey twice
AnyClass searchResult = searchKey(key);
if( searchResult != null ){
// Check if searchResult is an Employee object
if( searchResult instanceof Employee )
// Cast AnyClass to Employee
Employee empl = (Employee) searchResult;
// Your logic here...
// Set properties of the Employee object
empl.setPay(newPay);
// ...
return empl;
}
// Add 'else if' here, if you need to manage other Object types
// otherwise you can join previous if conditions
}
else
System.out.println("NO OBJECT WAS FOUND!");
return null;
}
Your code creates a new local Employee instance that dies when the method ends, its value will be lost because no object points to it.
for include pay "etemp.setPay(newPay);" you will change return object to Employee.
public Employee editObject(String key){
Employee etemp = new Employee(); //INCLUDED THIS AFTER EDIT
....
....
etemp.setPay(newPay); //INCLUDED THIS AFTER EDIT
return etemp;
}
because AnyClass hasn't "public double pay;"
I was given the main coding to do the sub class .
but I was stuck in these coding as shown at the below :
z.setName(z.obj1);
z.setID(z.obj2);
********** It should be the way to insert input. **************
========== The subClass I shown at the below was written by myself ==========
The main coding given as below :
public static void main(String[] args) {
StudReg z = new StudReg();
z.setName(z.obj1);
z.setID(z.obj2);
System.out.println(z.getName());
System.out.println(z.getID());
System.out.println(z.getJava());
System.out.println(z.getDatabase());
StuComputing obj3,obj4;
obj4 = new StuComputing();
obj4.setStudReg(z);
System.out.println(obj4.GPA().getGPA());
}
The subClass (StudReg) I've done as below :
public class StudReg {
//Data Member
String Name;
String ID;
double Java,Database;
//Constructor
public StudReg(){};
public StudReg(String a,String b){
Name = a;
ID = b;
};
//Name
public void setName(String n){
Name = n;
}
public String getName() {
return Name;
}
//Id
public void setID (String i){
ID = i;
}
public String getID (){
return ID;
}
//Java
public void setJava (double j){
Java = j;
}
public double getJava (){
return Java;
}
//Database
public void setDatabase (double d){
Database = d;
}
public double getDatabase (){
return Database;
}
//FUNCTION
public StudReg (StudReg gg){
double aa,bb;
//refer to data from MAIN
aa = this.getJava();
bb = this.getDatabase();
}
Another SubClass - StuComputing:
public class StuComputing {
//DATA MEMBER
public StudReg ss;
double GPA;
//CONSTRUCTOR
public StuComputing (){};
public StuComputing (double a1){
GPA = a1;
};
//StudReg
public void setStudReg (StudReg st){
ss = st;
}
public StudReg getStudReg(){
return ss;
}
//GPA
public void setGPA(double g){
GPA = g;
}
public double getGPA(){
return GPA;
}
Beside answer my problem, can you all show a simple example ?
So, I can understand it easily ><
Thanks
I have still no idea what you really want to do... try this
class StudReg {
String obj1 ;
String obj2 ;
double java ;
double database ;
String name ;
String id ;
public double getJava() {
return java;
}
public double getDatabase() {
return database;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getID() {
return id;
}
public void setID(String id) {
this.id = id;
}
public String getObj1() {
return obj1;
}
public void setObj1(String obj1) {
this.obj1 = obj1;
}
public String getObj2() {
return obj2;
}
public void setObj2(String obj2) {
this.obj2 = obj2;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
class StuComputing {
StudReg studReg;
GPA gpa;
public StuComputing() {
gpa = new GPA();
}
public StudReg getStudReg() {
return studReg;
}
public void setStudReg(StudReg sr) {
this.studReg = sr;
}
public GPA GPA() {
return gpa;
}
}
public class GPA {
double gpa;
public GPA() {
}
public double getGPA(){
return gpa;
}
}
You must have forgotten something. there is no "obj1" or "obj2" attribute in your class StudReg.
So how can we understand your problem? I think you need to ask your question again in other wording.
this is my current code to store rooms(it compiles fine) but in the UML there is a variable called addEquipment and there is also another class called Equipment to be defined. I'm having trouble wrapping my head around what I'm supposed to do with this. Am I supposed to create and call an object called Equipment? what goes in addEquipment?
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private String equipmentList;
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public String getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(String anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
}
//Create room object
public Room(int capacity, String equipmentList) {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
return "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
}
}
You can create a new class Equipment and modify your attribute equipmentList to be a List:
public class Equipment {
private String name;
public Equipment(String name) {
this.name = name;
}
}
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private List<Equipment> equipmentList = new ArrayList<Equipment>();
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public List<Equipment> getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(List<Equipment> anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
Equipment oneEquipment = new Equipment(newEquipment);
equipmentList.add(oneEquipment);
}
//Create room object
public Room() {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
String capacity=String.valueOf(getCapacity());
String room = "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
return room;
}
}
In the method addEquipment, you can create a new Equipment and add it to equipmentList, like code above.
An Equipment class could be anything. Lets assume the "Equipment"-class has a String called "name" as it's attribute
public class Equipment {
String name;
public Equipment( String name) {
this.name = name;
}
public String getName() {
return this.name
}
}
When you extend your Room class by the requested "addEquipment" method, you can do something like this.
public class Room {
... // Your code
private int equipmentIndex = 0;
private Equipment[] equipment = new Equipment[10]; // hold 10 Equipment objects
public void addEquipment( Equipment eq ) {
if ( equipmentIndex < 10 ) {
equipment[ equipmentIndex ] = eq;
equipmentIndex++;
System.out.println("Added new equipment: " + eq.getName());
} else {
System.out.println("The equipment " + eq.getName() + " was not added (array is full)");
}
}
}
Now when you call
room.addEquipment( new Equipment("Chair") );
on your previously initialized object of the Room-class, you will get
"Added new equipment: Chair"
Hope this helps a bit.
PS: The code is untestet (maybe there hides a syntax error somewhere)
I am a student working on a project creating classes with arrays to model composition. I have assume I have everything right so far but it seem that I am getting a problem with my print statement in the driver class. I am not sure if it about the way I am method chaining the two together. Any information would be thankful.
public class MyWord
{
private String word;
public MyWord(){
word = "Null";
}
public MyWord(String s){
word = s;
}
public String getWord(){
return word;
}
public void setWord(String w){
word = w;
}
public void print(){
System.out.println(word);
}
}
public class Page
{
private MyWord[] words = new MyWord[5];
private int pageNumber;
public Page(){
MyWord words[] = {} ;
pageNumber = 0;
}
public Page(MyWord[] a, int b){
words = a;
pageNumber = b;
}
public MyWord[] getWord(){
return words;
}
public int getPageNumber(){
return pageNumber;
}
public void setMyWord(MyWord[] a){
words = a;
}
public void setPageNumber(int b){
pageNumber = b;
}
public void print(){
System.out.print(" Page Number: " + pageNumber + " " + words);
}
}
public class Book
{
private Page[] p = new Page[5];
private String title;
public Book(){
Page[] p = {};
title = " ";
}
public Book(Page[] pa, String ti){
p = pa;
title = ti;
}
public Page[] getPage(){
return p;
}
public String getTitle(){
return title;
}
public void setPage(Page[] x){
p = x;
}
public void setTitle(String y){
title = y;
}
public void print(){
System.out.print("Book info:" + p + " " + title);
}
}
public class Series
{
private Book bookOne, bookTwo, bookThree;
private double price;
public Series(){
bookOne = null;
bookTwo = null;
bookThree = null;
price = 0;
}
public Series(Book one, Book two, Book three, double p){
bookOne = one;
bookTwo = two;
bookThree = three;
price = p;
}
public Book getBookTwo(){
return bookTwo;
}
public Book getBookOne(){
return bookOne;
}
public Book getBookThree(){
return bookThree;
}
public double getPrice(){
return price;
}
public void setBookOne(Book bookOne){
this.bookOne = bookOne;
}
public void setBookTwo(Book bookTwo){
this.bookTwo = bookTwo;
}
public void setBookThree(Book bookThree){
this.bookThree = bookThree;
}
public void setPrice(double price){
this.price = price;
}
public void print(){
System.out.println("Series info");
System.out.println("Book one:" + bookOne + " Book Two: " +bookTwo
+ " Book Three: " + bookThree + "Price: " + price);
}
}
public class Driver
{
public static void main(String args[]){
MyWord[] w1 = new MyWord[2];
w1[0] = new MyWord("Hello");
w1[1] = new MyWord("Hola");
Page[] p = new Page[2];
p[0] = new Page(w1, 20);
p.print();
}
}
p is of type Page[], i.e. "array of Page". And arrays don't have a print() method. So the statement p.print() doesn't compile (you should have said that in your question, and joined the exact error message).
To print all the pages of the array, you need to loop over the array:
for (Page page : p) {
page.print();
}
Please avoid single-letter variables, and use a plural form for arrays and collections: Page[] pages = new Page[2];