This question already has answers here:
How to convert an Array to a Set in Java
(19 answers)
Closed 2 years ago.
In my task I already put some cities in array but I now face a problem.
In main i did this:
City[] cities = enterCity(scanner);
In method enter city I had array of 3. So I needed to return name of a city and number of citizens.
In for loop I enter name and number of citizens. At the end of loop I did this:
cities[i]=new City(name, numbersOfCitizens);
and then returned it with City[] cities.
Now I need to improve my code with set.
In method I implemented:
Set<City> cities = new Hashset<>();
I failed to create method add. I tried with this to call it in main:
add.(City(name, numbersOfCitizens));
in City class and return City[] cities says inconvertible types ( so it cannot return anything). Is the right thing to call method like I do in main and if it is how to properly return all values. In class City I have usual get and set method.
Create Set
// Create new Set
Set<City> cities = new HashSet<City>();
// Add new City
cities.add(new City());
Convert Set in to array - option #1
City[] objects = cities.toArray(new City[0]);
Convert Set in to array - option #2
Manual copy:
City[] objects = new City[cities.size()];
int position = 0;
for (City city : cities) {
objects[position] = city;
position++;
}
Working example
public class SetExample {
private static Scanner scanner;
public static void main(String[] args) {
scanner = new Scanner(System.in);
Set<City> cities = readCities();
}
private static Set<City> readCities() {
Set<City> cities = new HashSet<City>();
int numberOfCities = 3;
for (int i = 0; i < numberOfCities; i++) {
City newCity = readCity();
cities.add(newCity);
}
return cities;
}
private static City readCity() {
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Numbers of citizens: ");
int numbersOfCitizens = scanner.nextInt();
return new City(name, numbersOfCitizens);
}
}
Printing
Example of the class:
class City {
private String name;
private int numbersOfCitizens;
public City(String name, int numbersOfCitizens) {
this.name = name;
this.numbersOfCitizens = numbersOfCitizens;
}
}
When you will use without adding toString() method so:
City city = new City("New York", 1234);
System.out.println(city);
you can expect output:
City#19469ea2
To print custom message, you have to override toString() method, for example generate "default" method in IntelliJ:
#Override
public String toString() {
return "City{" +
"name='" + name + '\'' +
", numbersOfCitizens=" + numbersOfCitizens +
'}';
}
or something simple like:
#Override
public String toString() {
return name + " " + numbersOfCitizens;
}
Related
I'm making an ArrayList of a type 'Item' that I've created. The class has a variable called name to describe the item. The items are stored in an ArrayList.
I cannot figure out how to reference the name variable because it is producing an error in the compiler that says cannot find symbol - variable name. Specifically, I reference it like this:
for (int i=0; i < theMenu.size(); i++) {
Item temp = theMenu.get(i);
if(temp.name == keyword)
System.out.println("test");
}
I've also tried referencing it like this:
for (int i=0; i < theMenu.size(); i++) {
if(theMenu.get(i).name == keyword)
System.out.println("test");
}
It produces the same error. Please help! Here is the relevant code:
import java.util.ArrayList;
import java.util.Scanner;
public class Doms {
public static class Item {
public Item(int itemID, String itemName, double itemPrice, double itemSalePrice, String itemSaleBeginDate, String itemSaleEndDate, ArrayList<Integer> itemReviews, ArrayList<String> itemComments) {
int id = itemID;
String name = itemName;
double price = itemPrice;
double salePrice = itemSalePrice;
String SaleBeginDate = itemSaleBeginDate;
String SaleEndDate = itemSaleEndDate;
ArrayList<Integer> reviews = itemReviews;
ArrayList<String> comments = itemComments;
}
}
public static void main(String[] args) {
// A list containing each Item and all of its contents
ArrayList<Item> items = new ArrayList<Item>();
// Create Item elements
ArrayList<Integer> reviews2 = new ArrayList<Integer>();
ArrayList<String> comments2 = new ArrayList<String>();
Item item2 = new Item(2, "Sour Cream Donut", 1.29, 1.29, "", "", reviews2, comments2);
items.add(item2);
//This part doesn't work
for (int i=0; i < theMenu.size(); i++) {
Item temp = theMenu.get(i);
if(temp.name == keyword)
System.out.println("test");
}
}
}
There is a lot going on with your code that needs work, but as suggested in the comments the main issue is that the variable name for example doesn't exist in your Item class, in fact no variables exist in your Item class.
To solve this you need to create class variables that you can reference from elsewhere, note how there are defined directly in the Item class not in the Item(...) method:
public static class Item {
//Create class variables
int id;
String name;
double price;
double salePrice;
String SaleBeginDate;
String SaleEndDate;
ArrayList<Integer> reviews;
ArrayList<String> comments;
public Item(int itemID, String itemName, double itemPrice, double itemSalePrice, String itemSaleBeginDate, String itemSaleEndDate, ArrayList<Integer> itemReviews, ArrayList<String> itemComments) {
//Use the values passed into the method and store them as class variables
id = itemID;
name = itemName;
price = itemPrice;
salePrice = itemSalePrice;
SaleBeginDate = itemSaleBeginDate;
SaleEndDate = itemSaleEndDate;
reviews = itemReviews;
comments = itemComments;
}
}
Now you can create an Item and get the values like normal:
//Create an item
Item item1 = new Item(1, "Apple Fritter", 1.49, 1.29, "February 1, 2021", "July 1, 2021", reviews1, comments1);
//Get the public values from the item:
System.out.println("ID: " + item1.id);
System.out.println("Name: " + item1.name);
System.out.println("Price: " + item1.price);
And you will get the following output:
ID: 1
Name: Apple Fritter
Price: 1.49
Note as per the comments to your question you need to use the String.equals(...) method to compare strings, you can't compare strings using ==. For example this is the correct way to compare the name string to the keyword string: if(temp.name.equals(keyword))
i hope someone can help me, i'm struggling with this since yesterday...
I'm working right now on a Hotel Management System project.
What i'm trying to do is, to put an array[] Clients into an ArrayList of Rooms and then set this room attribute to 'occupied = true' and save that so if i try to use that room for other client it doesn't let me.
Room class
public class Room {
private int number;
private float price= 30.5f;
private boolean occupied = false;
private Client[] hosts;
public Room(int number, Client[] hosts) {
this.number= number;
this.hosts= hosts;
}
public void setOccupied() {
this.occupied = true;
}
}
Client class
public class Client {
private String id;
private String name;
private String lastName;
public Client(String id, String name, String lastName) {
this.id = id;
this.name= name;
this.lastName= lastName;
}
}
This is what i've got on my Main so far... i'm calling the next function
public void checkIn(ArrayList<Room> myRooms){
int roomNumber;
String id;
String name;
String lastName;
Scanner input = new Scanner(System.in);
int people = input.nextInt();
Client[] array = new Client[people];
for (int i = 0; i < people; i++) {
System.out.println("Enter ID" + (i+1));
id = input.next();
System.out.println("Enter name " + (i+1));
name= input.next();
System.out.println("Enter last name " + (i+1));
lastName= input.next();
array[i] = new Client(id,name,lastName);
}
System.out.print("Assign to room number... : ");
roomNumber = input.nextInt();
myRooms.add(new Room(roomNumber, array));
//here i tried doing:
//room.set().setOccupied();
//room.set(roomNumber).setOccupied();
//but .set() expects an index...
}
Once i have this, i want to create a function that shows a list of rooms that are occupied
Excuse my english since i'm Spanish
Several ways to tackle this, probably what i would do is overload my room constructor so that you can set if it's occupied or not once you instantiate it like:
public Room(int number, Client[] hosts, boolean occupied)
{
this.number = number;
this.hosts = hosts;
this.occupied = true;
}
and in your checkIn() method just add true when instantiating your room inside the list:
myRooms.add(new Room(roomNumber, array, true));
Since you aren't creating a reference-able instance of Room when you call
myRooms.add(new Room(roomNumber, array));
you can't then say
room.setOccupied();
You can fix this two ways: First, as Bahij.Mik said, you could call this.occupied = true; in the Room constructor. Or, you could simply create a new instance of a Room in your checkIn method. This would look like:
Room newRoom = new Room(roomNumber, array);
newRoom.setOccupied();
whenever someone checks in.
As for creating a function to check which rooms are occupied, make an array of room numbers and then try:
public String[][] findOccupiedRooms(int[] roomNumbers) {
String[][] roomList = new String[roomNumbers.length][1];
for(int i = 0; i < roomNumbers.length; i++) {
if(roomNumbers[i].isOccupied() == true) {
roomList[i][0] = "" + roomNumbers[i];
roomList[i][1] = "occupied";
} else {
roomList[i][0] = "" + roomNumbers[i];
roomList[i][1] = "vacant";
}
}
return roomList[][];
}
This returns a 2-dimensional array that stores the room number and whether it is occupied or vacant. Not sure if this is exactly what you are looking for, but I hope it helps.
This question already has answers here:
how to print the index number of elements in the ArrayList using for each looping
(4 answers)
Closed 4 years ago.
This is my code
ArrayList<Restaurant> restaurant= new ArrayList<Restaurant>();
Inside Restaurant class,
#Override
public String toString() {
int i=1;
return "\n"+(i++)+". "+this.restaurantName +
"\t\t"+this.location;
}
I want to print like this
[ 1. pizzahut bangalore, 2. dominos delhi]
instead it prints
[ 1. pizzahut bangalore, 1. dominos delhi]
Help in code needed.
Here is another solution, I am not sure what actual problem you have, so just provide another possible solution. this might work for you.
public class Restaurant {
static int index = 1;
String restaurantName;
String location;
int curIndex;
Restaurant(final String restaurantName, final String location) {
this.restaurantName = restaurantName;
this.location = location;
this.curIndex = index++;
}
public static void main(final String[] input) {
final ArrayList<Restaurant> restaurant = new ArrayList<Restaurant>();
restaurant.add(new Restaurant("pizzahut", "bangalore"));
restaurant.add(new Restaurant("dominos", "delhi"));
restaurant.forEach(r -> System.out.println(r));
}
public String toString() {
return "\n" + curIndex + ". " + this.restaurantName +
"\t\t" + this.location;
}
}
ArrayList<Restaurant> restaurantList= new ArrayList<Restaurant>();
// your login to insert the elements in the array list
// iterate list
int index=1;
for(Restaurant r : restaurantList){
System.out.println(String.valueOf(index++)+": "+ r);
}
Inside Restaurant class,
#Override
public String toString() {
return this.restaurantName + "\t\t"+this.location;
}
I have to create a program which allows a user to entry information that includes a name,address,city,state,zip code,and age. A data structure ArrayList will be used to store information. Create classes to create objects and the classes methods to access information.
create a class called GroupArrayProject which will contain the main method.
You will create a class called People use ArrayList for name,address, city,state, zip, and age variables.
Create a method called AddRecord
AddRecord will be the method called to add records and its purpose is to call other methods that will be used.
These other methods(ex. addName()) will be called and used to enter the information for each ArrayList named above.
create a menu that allow for the program to:
a. show all the records you have entered
b. to show oldest or youngest
c. to find a record using first name or last name.
public class people {
String name, address, city, state, zipcode, age;
public people() {
name = null;
address = null;
city = null;
state = null;
zipcode = null;
age = null;
}
public void setpeople(String n, String ad, String c, String s, String z, String a) {
name = n;
address = ad;
city = c;
state = s;
zipcode = z;
age = a;
}
public string AddRecord
public String getpeople() {
String p = "name:" + name + "\n" + "address:" + address + "\n" + "city:" + city + "\n" + "state:" + state + "\n" + "zip code:" + zipcode + "\n" + "age:" + age;
return p;
}
}
public class GroupArrayProject {
public static void main(String[] args) {
{
ArrayList < String > list = new ArrayList < String > ();
people two = new people();
Scanner one = new Scanner(System.in);
System.out.println("type in your name,address,city,state,zipcode and age ");
String a = one.next();
String b = one.next();
String c = one.next();
String d = one.next();
String e = one.next();
String f = one.next();
two.setpeople(a, b, c, d, e, f);
System.out.println(two.getpeople());
}
}
}
That's what I've so far, I don't really know what to do next
rename your People class to Person
zipcode and age should be integers not Strings
create another constructor in the Person class with parameters that you will use to initialize your instance data
add getter and setter methods for each instance variable in the class.
add the following to the GroupArrayProject class:
private static List people = new ArrayList<>();
addRecord() should be in the GroupArrayProject class.
public void addRecord(Scanner input){
System.out.println("Name");
String name = input.next();
System.out.println("Address");
...
people.add(new Person(...));
}
That's the basics. You just need to create methods to search through your list of people and find matches and then your done.
I need to remove an element from an ArrayList using user's input.
Not really asking for a solution, but more of a guide in the right direction.
public class BFFHelper
{
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
}
public void addABFF()
{
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
System.out.println("Enter a nick name: ");
String nickName = keyboard.next();
System.out.println("Enter a phone number: ");
String cellPhone = keyboard.next();
BestFriends aBFF = new BestFriends(firstName, lastName, nickName, cellPhone);
myBFFs.add(aBFF);
}
public void changeABFF()
{
System.out.println("I am in changeBFF");
}
public void removeABFF()
{
//System.out.println("I am in removeABFF");
System.out.print("Enter friend's name to remove: ");
int i = 0;
boolean found = false;
while (i<myBFFs.size() && !found)
{
if (myBFFs.get(1).getfirstName().equalsIgnoreCase(firstName)) && (myBFFs.get(1).hetlastName().equalsIgnoreCase(lastName))
i++
}
}
public void displayABFF()
{
System.out.println("My Best Friends Phonebook is: ");
System.out.println(myBFFs);
}
}
this is what i have for my main class
public class BestFriends {
private static int friendNumber = 0;
private int friendIdNumber;
private String firstName;
private String lastName;
private String nickName;
private String cellPhoneNumber;
public BestFriends (String aFirstName, String aLastName, String aNickName, String aCellPhone)
{
firstName = aFirstName;
lastName = aLastName;
nickName = aNickName;
cellPhoneNumber = aCellPhone;
friendIdNumber = ++friendNumber;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getNickName()
{
return nickName;
}
public String getCellPhone()
{
return cellPhoneNumber;
}
public int getFriendId()
{
return friendIdNumber;
}
public String toString()
{
return friendIdNumber + ". " + firstName + " (" + nickName + ") " + lastName + "\n" + cellPhoneNumber + "\n";
}
}
Elements can be removed from an ArrayList using in various ways, for example by calling list.remove(index); or alternatively, by simply specifying the object to remove.
Just study the Javadoc for those methods. In addition to that, there are calls like removeAll() that remove all the arguments provided to the call.
Side note: there is at least one bug in your code:
if (myBFFs.get(1).getfirstName().equalsIgnoreCase(firstName)) && (myBFFs.get(1).hetlastName().equalsIgnoreCase(lastName))
should probably read.
if (myBFFs.get(i).getfirstName().equalsIgnoreCase(firstName)) && (myBFFs.get(i).hetlastName().equalsIgnoreCase(lastName))
Assuming that you are looping with i for a reason; and that you don't want to compare element1 to itself all the time.
And while we are at it: you could improve your abstractions. Obviously your program is about "humans". Humans normally have fixed names, haven't they. Meaning: have a class that just represents a human being; with final fields for information that can't change. Such fields are initialized via the constructor; and you dont have any setters for those.
How to Remove element of ArrayList from user's input?
One way to do such thing is to use an Iterator and call remove() when you find a match, something like this:
// Iterate over the list myBFFs
for (Iterator<BestFriends> it = myBFFs.iterator(); it.hasNext();) {
BestFriends bf = it.next();
if (/*some test here*/) {
// Found a match to remove
it.remove();
// Exit from the loop
// To be added if and only if you expect only one match otherwise keep iterating
break;
}
}
Assuming that you use Java 8, you can rely on the Stream API for such need.
In case you want to remove the first match
myBFFs.stream().filter(bf -> /*some test here*/).findFirst().ifPresent(myBFFs::remove);
This approach uses List#remove(Object o) to remove a unique object.
In case you want to remove all matches
myBFFs.removeAll(
myBFFs.stream().filter(bf -> /*some test here*/).collect(Collectors.toList())
);
This approach uses List#removeAll(Collection c) to remove a collection of objects.