How can I insert objects into an array? Here I have a class called HotelRoom which contains getter, setter, and the constructor method.
public class HotelRoom {
int roomNumber;
String roomGuest;
public HotelRoom (int room, String guest) {
roomNumber = room;
roomGuest = guest;
}
public int getRoom() {
return roomNumber;
}
public void setRoom() {
roomNumber = room;
}
public String getName() {
return roomGuest;
}
public void setName() {
roomGuest = guest;
}
And here I have the main method containing the array initializer and the objects. I've also inserted the objects into the array however, when compiling, the problem arises in the print command and it states: "cannot find symbol - variable HotelRoom". What am I doing wrong?
public class Hotel {
public static void main (String [] args) {
HotelRoom[] rooms = new HotelRoom [5];
HotelRoom guest1 = new HotelRoom(67, "Harry");
HotelRoom guest2 = new HotelRoom(98, "Bob");
HotelRoom guest3 = new HotelRoom(34, "Steven");
HotelRoom guest4 = new HotelRoom(99, "Larry");
HotelRoom guest5 = new HotelRoom(103, "Patrick");
rooms[0] = guest1;
rooms[1] = guest2;
rooms[2] = guest3;
rooms[3] = guest4;
rooms[4] = guest5;
System.out.println (HotelRoom);
}
}
This is because HotelRoom is a class, not an Object. If you have intentions of printing out all of the rooms, perhaps you could try something like:
for(final HotelRoom room : rooms)
System.out.printf("%s in room %d\n", room.getName(), room.getRoom());
Or you could override the toString() method in HotelRoom:
public String toString(){
return String.format("%s in room %d", roomGuest, roomNumber);
}
With the overridden toString() method, you can now modify your loop to:
for(final HotelRoom room : rooms)
System.out.println(room);
Or, if you want:
System.out.println(Arrays.toString(rooms));
HotelRoom is the name of the class. The objects are now in the rooms array. If you are wanting to print out the array, try printing rooms, or a particular place in the array, e.g
System.out.println(rooms[0].getName());
At first implement toString() in the HotelRoom:
public String toString() {
return roomNumber + " " + roomGuest;
}
And then print the right array:
System.out.println(Arrays.toString(rooms));
Related
I have already created an object and tried to set some variables but I cannot find the type of the variables that should I create in order to do not have any problem.
The part of the main class:
Menu menu = new Menu();
scanner.nextLine();
System.out.println("Give a code.");
String code = scanner.nextLine();
menu.setCode(code);
System.out.println("Give a main dish");
String MainDish = scanner.nextLine();
menu.setMainDishes(MainDish);
System.out.println("Give a drink.");
String Drink = scanner.nextLine();
menu.setDrinks(Drink);
System.out.println("Give a sweet.");
String Sweet = scanner.nextLine();
menu.setSweets(Sweet);
And the Menu class:
public class Menu {
ArrayList<String> MainDishes = new ArrayList<>();
ArrayList<String> Drinks = new ArrayList<>();
ArrayList<String> Sweets = new ArrayList<>();
private String code;
public ArrayList<String> getMainDishes() {
return MainDishes;
}
public void setMainDishes(ArrayList<String> mainDishes) {
MainDishes = mainDishes;
}
public ArrayList<String> getDrinks() {
return Drinks;
}
public void setDrinks(ArrayList<String> drinks) {
Drinks = drinks;
}
public ArrayList<String> getSweets() {
return Sweets;
}
public void setSweets(ArrayList<String> sweets) {
Sweets = sweets;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
Compliler give an error because of the String variables that I created.
Your menu class contains ArrayList variables and you try to assign a String to them. Instead of:
menu.setMainDishes(MainDish);
Try:
menu.getMainDishes().add(MainDish);
Also, common convention in Java is to start variables with lowercase, eg mainDish.
You are trying to pass a string when the methods are expecting an ArrayList of strings. If you want to do it the way you currently are, then create an ArrayList, put the user input into it, then pass that ArrayList to the methods that call for it.
How to pass multiple values to a single parameter for a particular method in java.
e.g. suppose i have a method with single parameter 'childname', that gets names of all the children in a family.
Now how can i pass multiple values to this parameter to get all different names.
public String getChildrenNames(String childname)
{
children= childname+ familyName;
return children;
}
You would typically implement this using either an Array, or a Collection.
eg:
public String[] getNamesOfChildren()
or
public Collection<String> getNamesOfChildren()
As people say you need to pass them as an Array, so your code should be like this:
String familyName = "Family";
public String[] getChildrenNames(String[] childnames)
{
String[] result = new String[childnames.length];
for(int i=0; i<childnames.length; i++)
{
result[i] = childnames[i] + " " +familyName;
}
return result;
}
public void main()
{
String[] childnames = {"Name1", "Name2", "Name3"};
String[] childnamesAux = getChildrenNames(childnames);
}
With this your childnamesAux variable should have: {"Name1 Family", "Name2 Family", "Name3 Family"}
If you can't change the signature of your method, then you can use concatenation, then in your method you can split this parameter for example :
String childname = firstname + "," + lastname;
getChildrenNames(childname);
so you can split this parametter to get multiple names,
String[] spl = childname.split(",");
But there are better ways then this, if you can change the signature of your method, so you can create a method which can take an array or list of names instead :
public String getChildrenNames(String...childnames) {
or
public String getChildrenNames(Lis<String> childnames) {
You can even create an Object for example :
class Person{
private String firstname;
private String lastname;
//getters and setters
}
Then your method should take an array or a list of Person Object :
public String getChildrenNames(List<Person> childname) {
You can try this
public static String child(String... name){
String[] array=name;
String tem;
if(name.length==1)
return name[0];
for(int counter=0; counter<array.length;counter+=2){
array[0]=name[counter]+name[counter+1];
}
tem=array[0];
return tem;
}
now if you call it
child("Paul","walker");
the output will be
Paul Walker
hope this helped
you can use var args like below
public String getChildrenNames(String... childname)
{
for(String s:childname)
{
children= childname+ s;
}
return children;
}
example
public class Test {
public static void main(String[] args) {
System.out.println(tes("s","d","s"));
}
static String tes(String... x)
{
String y="";
for(String s:x)
{
y=y+s;
}
return y;
}
}
output: sds
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 6 years ago.
This if my first question on stackoverflow. I can usually find answers myself but I'm having trouble with this one. I've got 2 objects, "Book", and "Periodical". These are subclasses to a class "Publication". Now, I'm trying to add 3 instances of "Book" and 3 instances of "Periodical" to an ArrayList. I'm having trouble figuring out how to do this.
With this current code, I get an error "no suitable method found for add(Book,Book,Book,Periodical,Periodical,Periodical).
Here is the current code:
import java.util.ArrayList;
import java.util.Date;
public class DriverProgram {
public static void main(String[] args) {
// Instantiate 3 instances of each object.
Book book1 = new Book(1234, 1, "James", 100, "Hello", "Berkwood Inc.", new java.util.Date(), "History");
Book book2 = new Book(2345, 2, "Ralph", 200, "Goodbye", "Shackles Co.", new java.util.Date(), "English");
Book book3 = new Book(3456, 3, "Julia", 300, "Hello Again", "Trustin Inc.", new java.util.Date(), "History");
Periodical periodical1 = new Periodical("Daily", "Dylan", "History 101", "History Inc.", new java.util.Date(), "History");
Periodical periodical2 = new Periodical("Weekly", "Jannette", "Mathematics 101", "Mathematics Inc.", new java.util.Date(), "Mathematics");
Periodical periodical3 = new Periodical("Monthly", "Patricia", "Science 101", "Science Inc.", new java.util.Date(), "Science");
// Create an array list of the Publication class type, and add the objects to it.
ArrayList <Publication> publications = new ArrayList<Publication>();
publications.add(book1, book2, book3, periodical1, periodical2, periodical3);
// Pass the array list to a method to loop through it and display the toString methods.
displayObjects(publications);
} // End of main
static void displayObjects (ArrayList<Publication> publications) {
// Loop through array list and display the objects using the toString methods.
for (Publication p : publications) {
System.out.print(p.toString());
} // End of for each loop
} // End of displayObjects
} // End of DriverProgram class
I've also tried changing:
publications.add(book1, book2, book3, periodical1, periodical2, periodical3);
To this:
publications.add(book1);
publications.add(book2);
publications.add(book3);
publications.add(periodical1);
publications.add(periodical2);
publications.add(periodical3);
Which rids my program of the compiler error, but then it just prints the "periodical3" object, 6 times. I'm not sure what I'm doing wrong. Any suggestions? Thank you in advance! :)
EDIT:
Here is my Book class:
public class Book extends Publication{
private static int isbn = 0;
private static int libraryOfCongressNbr = 0;
private static String author = "";
private static int nbrOfPages = 0;
// Constructor for Book class with parameters for each attribute.
public Book(int newISBN, int newLibraryOfCongressNbr, String newAuthor, int newNbrOfPages, String newTitle, String newPublisher, java.util.Date newPublicationDate, String newSubject) {
super(newTitle, newPublisher, newPublicationDate, newSubject);
isbn = newISBN;
libraryOfCongressNbr = newLibraryOfCongressNbr;
author = newAuthor;
nbrOfPages = newNbrOfPages;
}
/////////////////////////////////////////////////////// Getters ///////////////////////////////////////////////////////
int getISBN() {
return isbn;
}
int getLibraryOfCongressNbr() {
return libraryOfCongressNbr;
}
String getAuthor() {
return author;
}
int getNbrOfPages() {
return nbrOfPages;
}
/////////////////////////////////////////////////////// Setters ///////////////////////////////////////////////////////
void setISBN(int newISBN) {
isbn = newISBN;
}
void setLibraryOfCongressNbr(int newLibraryOfCongressNbr) {
libraryOfCongressNbr = newLibraryOfCongressNbr;
}
void setAuthor(String newAuthor) {
author = newAuthor;
}
void setNbrOfPages(int newNbrOfPages) {
nbrOfPages = newNbrOfPages;
}
//toString method for Book class
public String toString () {
StringBuilder result = new StringBuilder();
result.append("\nISBN: " + isbn + "\n");
result.append("\nPublisher: " + libraryOfCongressNbr + "\n");
result.append("\nAuthor: " + author + "\n");
result.append("\nNumber of Pages: " + nbrOfPages + "\n");
result.append("--------------------------------------------------------- ");
return super.toString() + result.toString();
} // End of toString
} // End of Book class
My Periodical class is identical, but here is my Publication class:
import java.util.Date;
public abstract class Publication {
// Data fields.
private static String title = "";
private static String publisher = "";
private static java.util.Date publicationDate;
private static String subject = "";
// Constructor for Publication class with parameters for each attribute.
public Publication(String newTitle, String newPublisher, java.util.Date newPublicationDate, String newSubject){
title = newTitle;
publisher = newPublisher;
publicationDate = newPublicationDate;
subject = newSubject;
}
/////////////////////////////////////////////////////// Getters ///////////////////////////////////////////////////////
String getTitle() {
return title;
}
String getPublisher() {
return publisher;
}
java.util.Date getPublicationDate() {
return publicationDate;
}
String getSubject() {
return subject;
}
/////////////////////////////////////////////////////// Setters ///////////////////////////////////////////////////////
void setTitle(String newTitle) {
title = newTitle;
}
void setPublisher(String newPublisher) {
publisher = newPublisher;
}
void setPublicationDate(java.util.Date newPublicationDate) {
publicationDate = newPublicationDate;
}
void setSubject(String newSubject) {
subject = newSubject;
}
//toString method for Publication class
public String toString () {
StringBuilder result = new StringBuilder();
result.append("\nTitle: " + title + "\n");
result.append("\nPublisher: " + publisher + "\n");
result.append("\nPublication Date: " + publicationDate + "\n");
result.append("\nSubject: " + subject + "\n");
return result.toString();
} // End of toString
} // End of Publication class
Let me know if you need anything else!
EDIT x2: Sorry, I realize my post is getting quite long.
So I've gotten rid of all "static" keywords from my class variables, or "data fields" as I've called them in my code. I then changed my code back to this code:
ArrayList <Publication> publications = new ArrayList<Publication>();
publications.add(book1);
publications.add(book2);
publications.add(book3);
publications.add(periodical1);
publications.add(periodical2);
publications.add(periodical3);
And it works! It executes as it should! I just one question though, since this code doesn't seem to work:
publications.add(book1, book2, book3, periodical1, periodical2, periodical3);
Is there a shorter way to add all of the objects to the ArrayList with out doing it one by one?
If I understand the problem correctly, you have 6 Publication objects, and you are only seeing the values of the most recently created one.
That would likely be caused because you have static class variables instead of instance variables.
For example
class A {
static int x; // class variable
int y; // instance variable
public A(int val) {
x = val; // All 'A' classes now have x = val;
y = val; // Only 'this' class has y = val;
}
}
If I were to run this
A a1 = new A(4);
A a2 = new A(5);
System.out.println(a1.x);
Then I would see it print 5 and not 4, which describes the scenario you are seeing because you have assigned all variables in the Publication class to those that you use during the last call of new Periodical.
The solution is to not use static variables if you want to have multiple instances of a class with their own values.
I am making a program that simulates a Store and a Member. I am trying to write a method, memberRegister2(). This method is the the Store class but calls the constructor from the Member class to make a member object. This method is to be passed the name, id and pinNumber as parameters and then creates the Member object, which is to be stored in a local variable 'member'. I have no idea how to do this. As you will see from the code below I have tried to use the 'Member member = new Member()' But i do not know how to make the parameters user input.
(P.S I am using BlueJ)
Here is my code for both classes hopefully making my question make more sense. I am very new to java so excuse bad coding.
public class Store
{
// instance variables
private String storeName;
private int total;
//Member member;
/**
* Constructor for objects of class Store
*/
public Store(String newStoreName, int newTotal)
{
// initialise instance variables
storeName = newStoreName;
total = newTotal;
}
//Accessor Methods
public String getStoreName()
{
return storeName;
}
public int getTotal()
{
return total;
}
public void memberRegister1(Member newMember)
{
System.out.println("Salford Thrifty " + storeName + ": Welcome " + newMember.getName() + " (id:" + newMember.getId() + ")" );
}
public void memberRegister2()
{
//Member member = new member(memberName, memberId, memberPinNumber);
}
//Mutator Methods
public void newStoreName(String newName)
{
storeName = newName;
}
public void newTotal(int newTotal)
{
total = newTotal;
}
}
and the Member class
public class Member
{
// instance variables
private String name;
private String id;
private String pinNumber;
/**
* Constructor for objects of class Member
*/
public Member(String memberName, String memberId, String memberPinNumber)
{
// initialise instance variables
name = memberName;
id = memberId;
pinNumber = memberPinNumber;
}
public Member()
{
// initialise instance variables
name = "Bob";
id = "ASD123";
pinNumber = "5678";
}
//Accessor Methods
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public String getPinNumber()
{
return pinNumber;
}
//Mutator Methods
public void newName(String newMemberName)
{
name = newMemberName;
}
public void newId(String newMemberId)
{
name = newMemberId;
}
public void newPinNumber(String newMemberPinNumber)
{
name = newMemberPinNumber;
}
}
I have been told to keep the variable at the top private and use pointers? Not sure what this means but it has not been explained to me very well.
You can a Scanner to read the user's input like so.
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
Then just initialize your member instance using the strings entered by the user.
String memberName, memberId, memberPin;
Scanner s = new Scanner(System.in);
System.out.println("Enter a name");
memberName = s.nextLine();
System.out.println("Enter an id");
memberId = s.nextLine();
System.out.println("Enter a pin");
memberPin = s.nextLine();
Member m = new Member(memberName, memberId, memberPin);
Also, you probably want to make pin, and maybe the id ints instead of strings.
Here's something I have from an old class that should show you how:
SavingsAccount myAccount = new SavingsAccount(200, 5);
So when you want to create an object from another class you have to use that second class to initialize it as shown above the SavingsAccount is like int it instantiates the object and then the two integers SavingsAccount(200, 5); is used because the method within the second class is instantiated with two integers of its own so the object you are creating must have two integers of its own. And what I mean by the method has two integer instantiated is as shown in the code below:
public SavingsAccount(double amount, double rate)
{
super(amount);
interestRate = rate;
}
if you do not instantiate a method with two objects within the parentheses then you do not need them within:
SavingsAccount myAccount = new SavingsAccount(200, 5);
I hope this helps any with your question i'm fairly new myself and am trying to help with as much as I can My course uses BlueJ as well and I know a good bit about BlueJ so I hope this helps.
class states{
List<String> cities = new ArrayList<String>();
public void add_city(String current_city){
this.cities.add(current_city);
}
}
class add_values{
public static void main(String [] args){
System.out.println("Enter the state name : ");
Scanner sc = new Scanner(System.in);
String user_state = sc.nextLine(); // need to create an object with the name from a string value
states user_state = new states();
....
....
}
}
Is there a way to create an object for a class with the name from a string.
If, user enters the state name as "Michigan", an object is created with "Michigan" which is got from scanner. and cities can be added for the state Michigan.
You will want to understand that objects have no names -- none, zero, zip. Yes, variables can have names, but that is not the same, since two or more variables can refer to the same object, and when that happens, which name is the name for the object? Again, neither/none since objects don't have names. As for variable names, they're way less important than you believe and almost don't exist in compiled code. What is most important are object references. Here an object can be associated with a String by means of a Map such as a HashMap<String, String> which is similar to an array or ArrayList that uses a String as its index rather than a number.
Now having said this, you can give your State class a String name field, and this may serve your purposes well.
i.e.,
import java.util.ArrayList;
import java.util.List;
public class State {
private String name;
private List<String> cities = new ArrayList<>();
public State(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void addCity(String city) {
cities.add(city);
}
public List<String> getCities() {
return cities;
}
#Override
public String toString() {
return "State of " + name + ", Cities: " + cities;
}
}
Which can be run like:
public class StateTest {
public static void main(String[] args) {
State illinois = new State("Illinois");
illinois.addCity("Chicago");
illinois.addCity("Peoria");
illinois.addCity("Springfield");
System.out.println(illinois);
}
}
You can do something different using HashMap. Hope this will help to achieve your goal. Here is the code:
class States{
List<String> cities = new ArrayList<String>();
public void add_city(String current_city){
this.cities.add(current_city);
}
}
class add_values{
public static void main(String [] args){
HashMap<String, States> userStatesMap = new HashMap<String, States>();
System.out.println("Enter the state name : ");
Scanner sc = new Scanner(System.in);
String user_state = sc.nextLine(); // need to create an object with the name from a string value
userStatesMap.put(user_state, new states());
....
....
}
}