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;
}
Related
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;
}
This question already has answers here:
The connection between 'System.out.println()' and 'toString()' in Java
(3 answers)
Closed 2 years ago.
consider the two classes below, why when I call the print method in the second class i get "blueblueblue is blue repeated" instead of "blueblueblue" despite the fact that tostring() was never called
public class Simple{
private String word;
private String phrase;
public Simple(int number, String w) {
word = w;
phrase = mystery(number, w);
}
private String mystery(int num, String s) {
String answer = "";
for (int k=0; k<num; k++) {
answer = answer + s;
}
return answer;
}
public String toString() {
return phrase + " is " + word + " repeated";
}
}
public class TestSimple{
public void print() {
Simple item = new Simple(3, "blue");
System.out.println(item);
}
}
yeah,the system out finally will invoke the
object's toString method. you can get the source code.
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 5 years ago.
hi i want to know how i can access to elements of arraylist in java?
i have this class .
class flight
{
public String start;
public String end;
public int timethatend ;
public int timethatstart;
flight ( int ts , int tf , String s , String e )
{
this.start = s;
this.end =e;
this.timethatend = tf;
this.timethatstart = ts;
}
}
and i have this arraylist in my main class
ArrayList<flight>list = new ArrayList<flight>();
now i want print the elements of arraylist i use this syntax
System.out.println(list.get(0));
but the out put is this
flight#1f96302
what should i do?
another question how i can change them for example i want change the time of takeoff the first flight.
This is printing the object reference to your flight object. You need to add a toString() method to your Flight class and use it to print the flight info. For example:
public String toString() {
return start + "," + timethatstart + "," + end + "," + timethatend;
}
When you print:
System.out.println(list.get(0).toString());
Add a toString method in the class like below:
class flight
{
public String start;
public String end;
public int timethatend ;
public int timethatstart;
flight ( int ts , int tf , String s , String e )
{
this.start = s;
this.end =e;
this.timethatend = tf;
this.timethatstart = ts;
}
#Override
public String toString() {
return "flight{" +
"start='" + start + '\'' +
", end='" + end + '\'' +
", timethatend=" + timethatend +
", timethatstart=" + timethatstart +
'}';
}
}
To add new flight elements in the arraylist, to the following:
flight f = new flight(1,2,"12","34");
ArrayList<flight> list = new ArrayList<flight>();
list.add(f);
To change the value of some element, do the following:
list.get(0).start = "1234";
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
Recently, I've learned something: I have no idea how to use toString methods.(If you've seen my last question, you'll get a prime example.)
Anyways, I was going through some unfinished programs of mine from an Intro to Java class I took last year and this one I just cannot finish. My effort to become a better programmer has faced the ultimate challenge: toString methods.
The basic overview is that I had to write a 'Grocery' store program where the ShoppingCart class was an ArrayList of Grocery Objects.
There's just one problem- when I run the program I get
Grocery.ShoppingCart#2eeb3c84
My old enemy, the toString() looks like it is required.
The output I should be getting is this:
[Tomatoes: 2.76 $1.39, Mac & Cheese: 6.0, $0.89]
now if I print out the Cart ArrayList (System.out.println(Cart)) I get this:
[Tomatoes, 2.76, $1.39, Mac & Cheese, 6.0, $0.89]
Exactly the output I should be getting.
How does this happen? How can I fix this?
When I print out the Cart Arraylist, I get the output I want (I still get the "Grocery.ShoppingCart#). I have to find some way to replace the "Grocery.ShoppingCart#[etc.]" with the ArrayList.
Anybody have any ideas?
Thanks!
-Chris
Bits of the ShoppingCart class:
ArrayList<Grocery> Cart = new ArrayList<Grocery>();
int size = Cart.size();
double tot = 0.0;
public ShoppingCart(){
}
...
public void printReceipt() {
Grocery temp = new Grocery();
double pr = 0.0;
double qu = 0.0;
String n = "";
String con = "IF YOU SEE ME SOMETHING IS WRONG!";
double gr = 0.0;
for(int k = 0; k < size; k++){
temp = Cart.get(k);
n = temp.getName();
qu = temp.getQuan();
pr = temp.getPrice();
tot = qu * pr;
con = n + ":" + " " + qu + ", " + pr + "\t\t Total: $" + tot;
}
System.out.println("====RECIEPT====");
System.out.println("Grand Total:\t" + "$" + totalPr());
}
Grocery Class Printing out ShoppingCart
public static void testShoppingCartClass ()
{
System.out.println ("Testing ShoppingCart class\n");
ShoppingCart myCart = new ShoppingCart();
System.out.println (" ShoppingCart using default constructor: ");
System.out.println ("\t" + myCart);
myCart.addItem (new Grocery("Tomatoes", 2.76, 1.39));
myCart.addItem (new Grocery("Mozzarella", 0.95, 4.59));
myCart.addItem (new Grocery("Mac & Cheese", 6, 0.89));
System.out.println ("\n ShoppingCart after adding three items: ");
System.out.println ("\t" + myCart);
myCart.removeItem (1);
System.out.println ("\n ShoppingCart after removing an item: ");
System.out.println ("\t" + myCart);
System.out.println ("\n\nPrinting receipt: \n");
myCart.printReceipt();
System.out.println ("\n\nDone testing ShoppingCart class\n\n");
}
You can override toString to return whatever you want. In your case, it looks like you want to do:
class ShoppingCart {
ArrayList<Grocery> cart;
...
#Override
public String toString() {
return cart.toString();
}
}
Java's default toString() method on any object will print out what you're seeing ("Grocery.ShoppingCart#[etc.]"). This is the Class with the object's hash code appended to the end of it.
From what I see in that output, you're calling .toString() on an instance of the ShoppingCart class which is why you're getting that output.
In order for that class to print out the contents of the ArrayList - Cart, which is a member of that class, you will need to override the toString() method of that class to print the contents of the ArrayList. Once it is overridden, your implementation of the toString() will be called rather than the default.
public String toString() {
// return the string that you want.
}
toString() is called on shoppingCart when you call System.out.println(shoppingCart) in order to retrieve the string to print.
Yes, you'll need a toString() on your ShoppingCart.
If I understand what you're trying to do though, may I suggest going with a more conventional Java bean approach? Here's a simplistic view.
Bean with getter and setters. A better name for this might be Item. You can change the types as needed as well.
public class Grocery {
public BigDecimal getQuantity() {
return quantity;
}
public void setQuantity(BigDecimal quantity) {
this.quantity = quantity;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private BigDecimal quantity;
private BigDecimal price;
private String name;
#Override
public String toString() {
return "Grocery{" +
"quantity=" + quantity +
", price=" + price +
", name='" + name + '\'' +
'}';
}
}
And your cart:
public class ShoppingCart {
List<Grocery> contents;
public void initialize() {
contents = new ArrayList<Grocery>();
}
public void addItem(Grocery item) {
contents.add(item);
}
public void removeItem(Grocery item) {
boolean wasRemoved = contents.remove(item);
if (!wasRemoved) {
System.out.println("Item not found in cart: " + item);
}
}
public List<Grocery> getContents() {
return contents;
}
#Override
public String toString() {
return "ShoppingCart{" +
"contents=" + contents +
'}';
}
}
And some class to run it:
public class CartRun {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
cart.initialize();
Grocery item = new Grocery();
item.setName("Tomatoes");
item.setPrice(BigDecimal.valueOf(2));
item.setQuantity(BigDecimal.valueOf(3));
cart.addItem(item);
System.out.println("Item="+item);
System.out.println("Cart="+cart);
}
}
Output:
Item=Grocery{quantity=3, price=2, name='Tomatoes'}
Cart=ShoppingCart{contents=[Grocery{quantity=3, price=2, name='Tomatoes'}]}
Also, stay away from capital letters (e.g., "Cart") for variable names because it looks like a static method call by convention.
What data structure should I use in the case described below:
I have a simple bean:
public class Points {
private String name;
private String address;
private int phone;
private int coord1;
private int coord2;
//getters+setters
}
I would like to create several beans and store them in some sort of data structure.
And be able to search with two parameters - name and address.
For example, user types in "7" - and it gives him back several object,
which name or address contains this character?
What data structure should i use and how do i search through it?
If it is important, I actually need this to implement into my android app -
i would like to search through my points on the map
Also I do not want to create a database so far, as there are only 20 of them.
Thank you very much in advance.
Try java's collection, e.g. hashmap. Although I ran this on PC, for 10000 items, with search
returned 3440 results, it took 76ms.
class Points {
String name;
String address;
int phone;
int coord1;
int coord2;
// getters+setters
};
class PointsIdentifier {
private String name;
private String address;
public PointsIdentifier(String name, String address) {
this.name = name;
this.address = address;
}
public boolean contains(String seq) {
return name.contains(seq) || address.contains(seq);
}
#Override
public boolean equals(Object obj) {
Points other = (Points) obj;
return name.equals(other.name) && address.equals(other.address);
}
#Override
public int hashCode() {
return name.hashCode() + address.hashCode();
}
};
class PointsCollection {
private Map<PointsIdentifier, Points> map;
public PointsCollection() {
map = new HashMap<PointsIdentifier, Points>();
}
public void add(Points p) {
map.put(new PointsIdentifier(p.name, p.address), p);
}
public List<Points> findIdsContaining(String seq) {
List<Points> resultList = new ArrayList<Points>();
for (Entry<PointsIdentifier, Points> entry : map.entrySet()) {
if (entry.getKey().contains(seq)) {
resultList.add(entry.getValue());
}
}
// optionally cache result
return resultList;
}
}
public class Question_11881630 {
public static void main(String[] args) {
PointsCollection places = createCollection(10000);
System.out.println("Collection created");
String seq = "1";
System.out.format("Searching for: \"%s\"\n", seq);
List<Points> verifySearch = verifySearch(places, seq);
//show(verifySearch);
}
private static void show(List<Points> verifySearch) {
int i = 1;
for (Points p : verifySearch) {
System.out.println(i + ": " + p.name + ", " + p.address);
i++;
}
}
private static List<Points> verifySearch(PointsCollection places, String seq) {
long start = System.currentTimeMillis();
List<Points> searchResult = places.findIdsContaining(seq);
System.out.println("Search results: " + searchResult.size());
long end = System.currentTimeMillis();
System.out.println("Operation time: " + formatTime(end - start));
return searchResult;
}
private static String formatTime(long elapsed) {
return elapsed + " miliseconds";
}
private static PointsCollection createCollection(int number) {
PointsCollection coll = new PointsCollection();
while (number > 0) {
coll.add(createSamplePoint(number));
number--;
}
return coll;
}
private static Points createSamplePoint(int number) {
Points p = new Points();
p.name = "VeryVeryLongName: " + number;
p.address = "VeryVeryLongLongAddress: " + number;
p.coord1 = 123;
p.coord2 = 456;
return p;
}
}
A trie seems a good fit. It is an efficient data structure to find all strings with a certain prefix.
If you want to use one of the existing java collections instead, you can use a TreeSet, and its floor() method to get the element before the needed prefix - and then start iterating the set while it still matches.
If you are looking for search by substring, and not only prefix - you might want to use a suffix tree instead.
An (inefficient) alternative that uses java's existing containers - is to store all substrings of your keys in a Set or a Map, but it will require quadric amount of space.