Project for Java - java

So my Java teacher wants us to write a program that simply says "Ben Barcomb is 19 years old" That's it, nothing more, nothing less.
Instead of using System.out.println like a normal person he wants us to use an instance variable in the Person class for the full name and age that must be private, he also wants a getter and setter method for the fullname and variable as well. This is the tester code I have, but I'm kind of stuck on the variable and getter/setter methods.
public class PersonTester {
public static void main(String[] args) {
Person p1 = new Person();
p1.setFullname("Bilal Gonen");
p1.setAge(76);
String myFullname = p1.getFullname();
int myAge = p1.getAge();
System.out.println(myFullname + " is " + myAge + " years old.");
}
}
public class Person{
private String myFullname;
private int myAge;
public String getFullname()
{
return myFullname;
}
public int getAge()
{
return myAge;
}
public Person(String aFullname)
{
myFullname = aFullname;
}
public void setFullname()
{
myFullname = aFullname;
}
}

Here is an example of a getter and setter. I am sure you can use this as a guide.
public class Person
{
private String firstName;
private String lastName;
public void setName(String f, String l)
{
firstName = f;
lastName = l;
}
public String getFirstName()
{
return firstName;
}
}
Short tutorial on setters and getters.

Not doing your homework for you, but I will provide some help on the getters and setters. Here's an example person class with one variable, add the others you need yourself.
public class Person {
int age;
public void setAge(int age) { // notice how the setter returns void and has an int parameter
this.age = age; // this.age means the age we declared earlier, while age is the age from the parameter
}
public int getAge() { // notice the return type, int? this is because the var we're getting is an int
return age;
}

Thanks to the help of everyone, as well as some of the research I did myself, I got the program to compile and run correctly, here is the source code. Thanks again to everyone who assisted!
public class PersonTester {
public static void main(String[] args) {
Person p1 = new Person();
p1.setFullname("Ben Barcomb");
p1.setAge(19);
String myFullname = p1.getFullname();
int myAge = p1.getAge();
System.out.println(myFullname + " is " + myAge + " years old.");
}
}
public class Person
{
private String myFullname;
private int myAge;
public String getFullname()
{
return myFullname;
}
public int getAge()
{
return myAge;
}
public void setAge(int newAge)
{
myAge = newAge;
}
public void setFullname(String aFullname)
{
myFullname = aFullname;
}
}

The valid code is as below, use getters for the String input of System.out.println()
Full test code is as below;
public class PersonTester {
public static void main(String[] args) {
Person p1 = new Person();
p1.setMyFullname("Bilal Gonen");
p1.setMyAge(76);
System.out.println(p1.getMyFullname() + " is " + p1.getMyAge() + " years old.");
}
}
class Person {
private String myFullname;
private int myAge;
public String getMyFullname() {
return myFullname;
}
public void setMyFullname(String myFullname) {
this.myFullname = myFullname;
}
public int getMyAge() {
return myAge;
}
public void setMyAge(int myAge) {
this.myAge = myAge;
}
}
And the output is as below;
Bilal Gonen is 76 years old.
Note: And it will make your job easier whenever a similiar project comes, when making a POJO class (in this example the Person class), use eclipse's (or any IDE's) "generate getters/setters" shortcut (on Eclipse, you can use it with Alt+Shift+S)

Related

I'm having a hard time understanding and implementing a constructor and I'm looking for some guidance

I'm learning about constructors, but the videos that I've watched don't seem to help and everything I find on google seems to describe it in an advanced way.
I want to write a simple program which takes two inputs, a name (String) and an id (integer) and then just outputs it as "id" - "name". So for example:
01 - hello
This is the program that I'm trying to fix:
import java.util.Scanner;
public class ConstructorTest {
public static void main(String[] args) {
ConstructorTest();
toString(null);
}
//Constructor
public ConstructorTest(){
Scanner name = new Scanner(System.in);
Scanner id = new Scanner(System.in);
}
// Method
public String toString(String name, int id) {
System.out.print(id + " - " + name);
return null;
}
}
The errors that I get, are saying that my methods and constructors are undefined.
A constructor creates ("constructs") a new object. You can then call methods against that object.
Here's a simple object:
public class MyObject {
private int id;
private String name;
public MyObject(int id, String name) {
this.id = id;
this.name = name;
}
// Other methods here, for example:
public void print() {
System.out.println(id + " " + name);
}
}
You would call this constructor like this:
MyObject thing = new MyObject(1, "test");
And then you could call its method like this:
thing.print();
So for your example, what you'd do in your main method is first prompt the user for id and name, then create an object using a constructor, and then call a method on the constructor.
public class ConstructorTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// get the id and name from the scanner (I would suggest using prompts)
String name = in.nextLine();
int id = in.nextInt();
// create an object:
ConstructorTest myObject = new ConstructorTest(id, name);
// call the method:
String myString = myObject.toString();
// print the result:
System.out.println(myString);
}
// private variables, effectively the "properties" stored by the object:
private int id;
private String name;
// constructor:
public ConstructorTest(int id, String name) {
this.id = id;
this.name = name;
}
// method
#Override // because this is a method in java.lang.Object and we're overriding it
public String toString() {
return id + " - " + name;
}
}
Try this:
import java.util.Scanner;
public class ConstructorTest {
private int id;
private String name;
public static void main(String[] args) {
String name = args[0];
int id = Integer.valueOf(args[1]);
ConstructorTest ct = new ConstructorTest(name, id);
System.out.println(ct);
}
public ConstructorTest(String n, int i) {
this.id = i;
this.name = n;
}
// Method
public String toString() {
return String.format("%d - %s", id, name);
}
}
Never, ever put I/O in a constructor.

set field equal to method's parameter in java

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/

Creating an object and calling it

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)

Constructor + Inheritance support

I am fairly new to Inheritance, and I'm not sure if I am doing it right but I seem to be on the right track. The program runs fine except the output I am getting isn't right. I think the problem is to do with my constructors.
public class Person {
protected static String name;
protected static int birthYear;
public Person(String name, int birthYear) {
}
public String name (String n) {
n = name;
return n;
}
public int birthYear (int bY) {
bY = birthYear;
return bY;
}
#Override
public String toString() {
return String.format(name + birthYear);
}
}
public class Student extends Person {
protected String major;
public Student(String name, int birthYear, String major) {
super(name, birthYear);
major = "";
}
public String major(String maj) {
maj = major;
return maj;
}
public String toString() {
super.toString();
return super.toString() + major;
}
}
public class Instructor extends Person {
protected static int salary;
public Instructor(String name, int birthYear, int salary) {
super(name, birthYear);
salary = 0;
}
public int salary(int sal) {
sal = salary;
return sal;
}
public String toString() {
super.toString();
return super.toString() + salary;
}
}
public class PersonTester {
public static void main(String[] args) {
Person p = new Person("Perry", 1959);
Student s = new Student("Sylvia", 1979, "Computer Science");
Instructor e = new Instructor("Edgar", 1969, 65000);
System.out.println(p);
System.out.println("Expected: Person[name=Perry,birthYear=1959]");
System.out.println(s);
System.out.println("Expected:" +
"Student[super=Person[name=Sylvia,birthYear=1979],major=Computer]");
System.out.println(e);
System.out.println("Expected:" + "Instructor[super=Person[name=Edgar,birthYear=1969],salary=65000.0]");
}
}
OUTPUT I AM GETTING:
null0
Expected: Person[name=Perry,birthYear=1959]
null0null
Expected: Student[super=Person[name=Sylvia,birthYear=1979],major=Computer Science]
null00
Expected: Instructor[super=Person[name=Edgar,birthYear=1969],salary=65000.0]
Try changing your constructor in Person to:
public Person(String name, int birthYear) {
this.name = name;
this.birthYear = birthYear;
}
Currently, the constructor has an empty body, so when you call super(name, birthYear); in the subclass constructor, nothing actually happens.
Your Student constructor also has an error. You forgot to initialize the major field.
public Student(String name, int birthYear, String major) {
super(name, birthYear);
this.major = major;
}
You have the same problem in the Instructor constructor...
public Instructor(String name, int birthYear, int salary) {
super(name, birthYear);
this.salary = salary;
}
Finally, you need to take away the static keywords before the fields in Person. This is because static ensures, that there will always be one (and only one) instance of those fields per class, as opposed to one per instance, like you want it to be:
protected String name;
protected int birthYear;
Same thing for the salary field in Instructor.
n = name; this causing your problem. It must be name = n;. All your setter function contain this problem, correct them all and tell me result.

new to java constructor help needed

I have an past exam question that says:
"Create a class Element that records the name of the element as a String and has a public method, toString that returns the String name. Define a constructor for the class (that should receive a String to initialise the name)."
I gave it a go and don't where to go from here...
main class is:
public class builder {
public static void main(String[] args) {
element builderObject = new element(elementName);
}
}
and constructor is:
import java.util.*;
class element {
public int getInt(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first number");
String elementName = scan.nextLine();
System.out.println("%s");
}
public String toString() {
return elementName;
}
}
Don't get frustrated. Please read java tutorials first and understand the concepts. your exam question is very clear on what you need to do. Atleast for this question, you need to know what is constructor, the purpose of having toString() in a class.
May be the below can help you.
public class Element {
private String elementName;
public Element(String elementName) {
this.elementName = elementName;
}
#Override
public String toString() {
return elementName;
}
}
I can't think of a way to explain this without actually giving the answer, so....
public class Element { /// Create class Element
private final String name; // Record the 'name'
public Element(String name) { // constructor receives and sets the name
this.name = name;
}
public String toString() { // public method toString() returns the name
return name;
}
}
You are missing the constructor itself. The point of constructors is to initialize the object, usually by saving the given parameters to data members.
E.g.:
class Element {
/** A data member to save the Element's name */
private String elementName;
/** A constructor from an Element's name*/
public Element(String elementName) {
this.elementName = elementName;
}
#Override
public String toString() {
return elementName;
}
}
class Element {
private String name = "";
/**
/* Constructor
/**/
public void Element(final String name){
this.name = name;
}
#Override
public String toString(){
return name;
}
}
You don't have a constructor in there. A constructor typically looks something like this:
public class MyClass {
private String name;
private int age;
//This here is the constructor:
public MyClass(String name, int age) {
this.name = name;
this.age = age;
}
//here's a toString method just for demonstration
#Override
public String toString() {
return "Hello, my name is " + name + " and I am " + age + " years old!";
}
}
You should be able to use that as a guideline for making your own constructor.
class Element
{
private String name = "UNSET";
public String getName() { return name; }
public Element(String name) {
this.name = name;
}
public String toString() {
return getName();
}
}
You are missing a constructor you might be looking for something like this
public class Element{
private String name;
public Element(String name){ //Constructor is a method, having same name as class
this.name = name;
}
public String toString(){
return name;
}
}
A note
I take you are starting with java, In java class names usually start with capital letter, thus element should be Element. Its important that one picks up good habits early..

Categories

Resources