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..
Related
I was practicing setter & getter in Java. I thought what if my code will through an error if user have set Employee name incorrect i.e. "123" or "#qre23" which can't be someone's name in real .Here is my code, suggest me what to upgrade ?
class MyEmployee {
private int id;
private String name;
public void setName(String name){
this.name = name;
}
public void getName(){
System.out.println("\n Your Employee Name is : " + this.name);
}
}
public class Main {
public static void main(String[] args) {
MyEmployee myEmployee = new MyEmployee();
myEmployee.setName("209");
myEmployee.getName();
}
}
Match the string with the Regex using matches()
public void setName(String name){
if(name.matches("^[a-zA-Z ]*$"))
this.name = name;
else
//throw error
}
You can do it in many different ways depending on what regex you want but this is one way to do it. Also make sure your getter returns a name. Right now, your getter doesn't return the name.
class MyEmployee {
private int id;
private String name;
public void setName(String name){
String regx = "^[\\p{L} .'-]+$";
boolean match = Pattern.matches(regx, name);
if(match){
this.name = name;
}
}
public String getName(){
System.out.println("\n Your Employee Name is : " + this.name);
return this.name;
}
}
this is main method
public static void main(String[] args) {
Author[] authors=new Author[2];
for(int i=0;i<=authors.length;i++);
authors[0]=new Author("suru","suru#qwe.com","m");
authors[1]=new Author("aksh","aksh#qwe.com","m");
for(int i=0;i<=authors.length;i++);
System.out.println(authors);
Book book=new Book("java",authors,200,2);
System.out.println(book);
now i created 2nd class authoer with getter and setter
private String name;
private String email;
private String gender;
public Author (String name,String email, String gender)
{
this.name=name;
this.email=email;
this.gender=gender;
}
noow i created new class Book
public class Book {
private String name;
private Author[] author;
private double price;
private int qty=0;
public Book(String name,Author[] author,double price, int qty) {
this.name=name;
this.author=author;
this.price=price;
this.qty=qty;
}
when i run this program the output give the memory adress ho can i print theese detail
You need to override toString() method in the class Author.
For example:
#Override
public String toString() {
return "Author [name=" + name + ", email=" + email + ", gender=" + gender + "]";
}
When you pass as argument of the method System.out.println() name of variable, method toString() of the class of that variable is being called. If you don't override that method in class Author or Book, toString() method inherited by these classes from Object class is being called (all classes in Java inherit from Object class). By default, this method prints address in memory for classes with toString() not defined in their bodies. There is a simple example, how you can override it in Author method:
class Author {
#Override
public String toString() {
return "Author name: " + this.name + "\nAuthor email: " + this.email + "\nAuthor gender : " + this.gender;
}
To print contents of an array (in your example to print each Author contained in Author[] authors) you might want to use one of these way to achieve that (as Author[] or Book[] is actually a type of array and not a type of Book or Author and has its own toString() method printing address in memory) :
Create a loop iterating over each element of authors array:
for (Author author : authors) {
System.out.println(author + "------"); // toString() method of each Author is called and added simple separator
}
Call Arrays.toString(authors) method. Class Arrays is provided to let you manipulate arrays in many different ways. You can read about this class in Java API documentation. This is a part of what documentation says about Arrays.toString() method:
Returns a string representation of the contents of the specified array. If the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object, which describes their identities rather than their contents.
package oops;
public class Main {
public static void main(String[] args) {
Author[] authors=new Author[2];
for(int i=0;i<=authors.length;i++);
authors[0]=new Author("suru","suru#qwe.com","m");
authors[1]=new Author("aksh","aksh#qwe.com","m");
for(int i=0;i<=authors.length;i++);
System.out.println(authors);
Book book=new Book("java",authors,200,2);
System.out.println(book);
}
}
package oops;
public class Author {
private String name;
private String email;
private String gender;
public Author (String name,String email, String gender)
{
this.name=name;
this.email=email;
this.gender=gender;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String toString() {
return name+ " " +email+ " " +gender+ " ";
}
package oops;
public class Book {
private String name;
private Author[] author;
private double price;
private int qty=0;
public Book(String name,Author[] author,double price, int qty) {
this.name=name;
this.author=author;
this.price=price;
this.qty=qty;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public String getName() {
return name;
}
/*public Author[] getAuthor() {
return author;
} */
public Author[] getAuther() {
for (int i=0;i<=author.length;i++);
return author;
}
public String toString() {
return name+" "+author+" "+price+" "+qty+" ";
}
public Author[] getAutherNames() {
for (int i=0;i<=author.length;i++);
return author;
}
}
this is my full program
You an override toString() or you can print the attributes of the object directly as follows:
Book b = new Book(/*args*/);
System.out.println("Name: " + b.name);
// continue printing all the attributes in the same way
You can try this instead of overriding toString() method in the object class.
Hope this helps...
This is the class that contains main.
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
String name;
Random r = new Random();
int number = 1 + r.nextInt(3);
System.out.println(number);
if (number == 1) {
name = "Kobe";
}
else if (number == 2) {
name = "Mamba";
}
else {
name = "lol";
}
RandomTest2 object = new RandomTest2(name);
System.out.println(object.toString());
}
}
This class contains other methods.
public class RandomTest2 {
private String name;
public RandomTest2(String name) {
name = name;
}
public String getName() {
return name;
}
public String toString() {
return getName();
}
}
If I remove the If statement and I assign a value directly to name, it works..
I just want to randomly assign properties to the object.
You just missed a this in your constructor:
public RandomTest2(String name) {
this.name = name;
}
Without it, you are just assigning the name parameter to itself.
No worries, this gets every Java coder at least once ;-)
Instead of name = name as shown below
RandomTest2(String name) {
name = name;
}
Try
this.name=name;
on this function:
public RandomTest2(String name) {
name = name;
}
the compiler is understand that you assign name to itself not for the name variable on RandomTest2. So change it to this.name = name.
class RandomTest2 -> constructor method -> this.name = name
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)
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)