I have an error in this code
public Hotel()
{
occupiedRooms = new HashSet<Room>();
PapersOrdered = new HashMap <String,ArrayList<String>>();
}
public String getGuest(String roomNo)
{
for (Room room; occupiedRooms;)
{
if(room.getRoomNo().equals(roomNo)) return room; getGuest();
return "room " + roomNo + " is not occupied" ;
}
}
and the occupied rooms gets an error saying java.util.<>Hashset cannot be converted to boolean,
what is the best way to correct this.(All code is not in here but just what is relevant)
Yes, a HashSet is not a boolean and cannot be converted to a boolean, and the regular for loop expects a boolean expression in the middle section (the section that determines when the loop terminates).
If you want to iterate over all the values in the set, you can use the enhanced for loop :
for (Room room : occupiedRooms)
{
if(room.getRoomNo().equals(roomNo))
return room;
getGuest();
return "room " + roomNo + " is not occupied" ;
}
Not sure how much sense your for loop makes, though, as it would always return something after the firstroom is tested, so the remaining rooms won't be checked.
Related
Pardon my phrasing of the question, I'm still fairly new to Java so I wasn't sure how to word it. Basically, I have created an inventory and added 2 different methods:
public class Inventory
{
String name;
Items myItems = new Items();
boolean addFoodItem;
boolean addDrinkItem;
boolean addToyItem;
boolean addCampingItem;
boolean removeFoodItem;
boolean removeDrinkItem;
boolean removeToyItem;
boolean removeCampingItem;
ArrayList<Objects> inventory = new ArrayList<Objects>();
Objects myObjects = new Objects(name);
public boolean AddToInventory (boolean addFoodItem, boolean addDrinkItem, boolean addToyItem, boolean addCampingItem)
{
if (addFoodItem)
{
inventory.add(myItems.foodItem);
System.out.println("You have added 1 " + myItems.FoodItem.name + " to your
inventory.");
}
if (addDrinkItem)
{
inventory.add(myItems.drinkItem);
System.out.println("You have added 1 " + myItems.DrinkItem.name + " to your
inventory.");
}
if (addToyItem)
{
inventory.add(myItems.toyItem);
System.out.println("You have added 1 " + myItems.ToyItem.name + " to your
inventory.");
}
if (addCampingItem)
{
inventory.add(myItems.campingItem);
System.out.println("You have added 1 " + myItems.CampingItem.name + " to your
inventory.");
}
return true;
}
public boolean RemoveFromInventory(boolean removeFoodItem, boolean removeDrinkItem, boolean
removeToyItem, boolean removeCampingItem)
{
if (removeFoodItem)
{
inventory.remove(myItems.foodItem);
System.out.println("You have used 1 " + myItems.foodItem.name + " from your
inventory.");
}
if (removeDrinkItem)
{
inventory.remove(myItems.drinkItem);
System.out.println("You have used 1 " + myItems.drinkItem.name + " from your
inventory.");
}
if (removeToyItem)
{
inventory.remove(myItems.toyItem);
System.out.println("You have used 1 " + myItems.toyItem.name + " from your
inventory.");
}
if (removeCampingItem)
{
inventory.remove(myItems.campingItem);
System.out.println("You have used 1 " + myItems.campingItem.name + " from your
inventory.");
}
return true;
}
public void GetInventory()
{
for (Objects items : inventory)
{
System.out.println(items.name);
}
}
There will be more objects that will be added to this script which is why I am looking to see if there is a potentially more efficient way of doing this. The Items.java class simply creates the objects and the Objects.java class only returns the name of the object so it can be printed. All of this code works, but as I add more items, I need to keep switching the booleans to true and false in other classes just to have the AddToInventory and RemoveFromInventory methods to run.
So my question is, what is a more efficient way of checking if I need to add to and/or remove multiple objects from an inventory (ArrayList). I have considered using a method for each individual check (for add to or subtracting from inventory), but ruled it out as it is not much different from the methods I have above.
Thanks everyone!
My thoughts behind this are if I call this method from another class and switch the boolean to true, these methods execute the code within the if statement and will either add or remove from the "inventory" ArrayList. The inefficiency that I see is when calling this method from another class, I have to include all the booleans in the arguments for example:
if (//add check here)
{
Inventory.AddToInventory (boolean addFoodItem = true, boolean
addDrinkItem = false, boolean addToyItem = false, boolean addCampingItem
= false)
}
With more items being added, this is quite the chunk of text. This is what I'd like to clean up if possible.
If I were you, I would do an Enum representing every item, and after the operation is done (addition/removal), return that Enum. This way, you will know on which kind of item was performed the operation.
Also, in your current code, instead of multiple ifs, it would look better to have a switch case.
I used #racraman suggestion and created a super class with subclasses for all items so there isn't this big long argument of item booleans in a method. Since then I have added 10 new objects so that list would have been pretty long and ugly to repeat everytime!
I have this method which takes n number of arguments and search for a book in an arrayList using couple of arguments. .
How can i make it smaller?
How to sort books by category or author?
thank you in advance.
Here is my method
// search for a book using multiple criteria
static void bookSearch(String... varg) { // take varg as parameter
String title = ""; // place holders
String author = "";
if (varg.length > 1) { // check varg length
title = varg[0]; // if it is greater than 1 initialize needed arguments
author = varg[1];
} else {
title = varg[0]; // else initialize the first argument
}
for (Book book : bookList) {
/*
* if the title is the same and there is a second argument that
* match author's name print found it
*/
if (book.getTitle().equals(title)) {
if (author.isEmpty() ^ (book.getAuthor().getfName() == author)) {
System.out.println(" \"" +
title +
"\" founded at: " +
bookList.indexOf(book));
break;
}// end of if
} else if (bookList.indexOf(book) == bookList.size() - 1) {// if not found
System.out.println("cant find \"" + title);
}// end of else
} // end of for loop
} //end of search method
In Java8 you can use lambdas and functions to get flexible filter book function.
E.g. you have following Book class:
class Book {
private String author;
private String title;
}
The book filter function could look like this:
BiFunction<List<Book>, Predicate<Book>, List<Book>> BOOK_FILTER =
(books, fields) -> books.stream().filter(fields).collect(Collectors.toList());
Then, all you need is just build required Predicate and use this function.
public static List<Book> findBookByPredicate(List<Book> books, String author, String title) {
Predicate<Book> byAuthor = book -> book.getAuthor().equals(author);
Predicate<Book> byTitle = book -> book.getTitle().equals(title);
return BOOK_FILTER.apply(books, byAuthor.and(byTitle));
}
As you can see, you're not limited only certain number of Book fields. You can combine it as you like; BOOK_FILTER function stays the same.
You can default title to varg[0] and set author if varg.length is greater than one with a ternary. I would prefer a standard loop with a index counter (since otherwise you must search again to determine the index). Next, you need to complete the loop before declaring the title isn't found (I would use a boolean to maintain that state). Next, you logically need an or (not a xor) to check that the author argument is present and not empty before checking the book author. I would prefer formatted io. Like,
static void bookSearch(String... varg) {
String title = varg[0], author = varg.length > 1 ? varg[1] : "";
boolean found = false;
for (int i = 0; i < bookList.size(); i++) {
Book book = bookList.get(i);
if (book.getTitle().equals(title)
&& (author.isEmpty() || book.getAuthor().getName().equals(author))) {
System.out.printf("\"%s\" found at: %d%n", title, i);
found = true;
break;
}
}
if (!found) {
System.out.printf("cant find \"%s\"%n", title);
}
}
You can use java 8 lamda expression for this.
Ex.
List<String> lines = Arrays.asList("spring", "node", "mkyong");
//Here pass your collection and filter as per your requirement
List<String> result = lines.stream()
.filter(line -> !"mkyong".equals(line))
.collect(Collectors.toList());
Aside from using lambda expression, other way to make your code a little shorter would be to implement equals method for your Book class where you can compare two Book objects for equality by their title and author. Then instead of:
if (book.getTitle().equals(title)) {
if (author.isEmpty() ^ (book.getAuthor().getfName() == author)) {
System.out.println(" \"" + title + "\" founded at: "
+ bookList.indexOf(book));
break;
}// end of if
you can just use:
Book searchForBook = new Book();
searchForBook.setAuthor(author); //ins
searchForBook.setTitle(title);
for (Book book : bookList) {
if (book.equals(searchForBook)){
System.out.println(" \"" + title + "\" found at: "
+ bookList.indexOf(book));
break;
}
You can also make the creation of object searchForBook one line only, if you add proper constructors in your Book class.
On sorting the ArrayList - you can either make Book implement Comparable and use Collections.sort(bookList) or use a Comparator instead and use Comparator and again use Collections.sort before you use the collection, to have it sorted the way you want.
Your code can be shortened like this:
static void bookSearch (String... varg) {
String author = "";
String title = varg[0];
if (varg.length > 1) {
author = varg[1];
}
for (Book book : bookList) {
if (book.getTitle().equals (title)) && (author.isEmpty() || (book.getAuthor().getfName() == author)) {
System.out.println(" \"" + title + "\" founded at: " + bookList.indexOf(book));
return;
}
}
System.out.println("cant find \"" + title);
}
Title doesn't need to be in if and else branch. Just initialize on declaration.
Take the ternary operator from Elliot if you like
Your outer if only has the inner if (title/author). This can be replaced by &&.
Just return instead of breaking.
With the premature return, you don't need else anymore.
A boolean predicate 'matches' which does the same thing in the Book class might be preferred. Sorting can be a good idea, if you don't have to resort by different criteria often and if you search for multiple books - then it can pay off.
A boolean return or a return of the index, where the book was found, might be more flexible. But for reporting the index, I would use a classical for loop, where you get it by the same iteration.
Returning the index would allow to remove the System.outs, so that the caller can decide, how to handle the event: Order a book via net, print to stdout, output with Swing oder JavaFX or whatever.
A pure compareTo would allow efficient search algorithms to find many book in big lists fast and smooth integration in the new Stream collections.
Using varg seems to be a bad idea to me, since it opens the door wide for getting the parameter order wrong.
int bookSearch (String title, Optional[String] author) {
expresses more clearly what you want - many IDEs support parameter names.
I am trying to print my arraylist but i don't know why my printing does not print line by line of IntegerPair in each index of Adjlist:
private ArrayList<ArrayList<IntegerPair>> AdjList; //outer arraylist
private ArrayList<IntegerPair> storeNeighbour; //inner arraylist
private IntegerPair pair;
This is my snippet:
for (ArrayList<IntegerPair> l1 : AdjList) {
for (IntegerPair n : l1) {
System.out.println( n + "# ");
}
}
The default behavior of ArrayList.toString() is to return a single string containing a (somewhat) beautified list of calls to toString() on each element in the list.
So, long story short: you are almost there; the one thing that is missing:
#Override
public String toString() {
...
within your class IntegerPair.
Like:
public class IntegerPair {
private final Integer first;
private final Integer second;
...
#Override
public String toString() {
return "(" + first + "/" + second ")";
}
or something alike. Without overriding toString() your class will fall back on the default implementation given in java.lang.Object; and that method returns class name + hashcode number (and is thus not so human-readable).
Here :
for (ArrayList<IntegerPair> l1 : AdjList) {
for (IntegerPair n : l1) {
System.out.println( n + "# ");
}
}
You don't differentiate each printed List.
As a result, you will have a series of output without knowing those associated to a same list.
A more readable print would be :
for (ArrayList<IntegerPair> l1 : AdjList) {
System.out.println("ArrayList with :");
for (IntegerPair n : l1) {
System.out.println( n + "# ");
}
}
You don't specify your output. So I don't suppose toString() is or not overridden. If it is not overridden you should either override it to render the String expected here : System.out.println( n + "# ");, or you should specify the content to render here :
System.out.println( n.getOne() + "," + n.getOther() + "# ");
As a side note, toString() is designed for debugging/logging, not for displaying functional messages as an object could be rendered in a way for a case and in another way for other cases.
I'm sorry if the question is a bit vague so i'll try to explain it.
I got this code:
public String toString()
{
String s = "text.\n";
for (Klus k : alleKlussen)
{
s += k.toString() + ".\n";
}
return s;
}
But I want to make different loops for different conditions.
For example, "Klus" has a couple of variables like: status, date etc.
I'm not very experienced with java yet, but would it be possible to do something like this:
for (Klus k : alleKlussen; status = "completed")
{..}
I know this is wrong but I'd like it to show all "Klus" objects where the status is "completed" and all "Klus" objects where the statis is "not completed".
Thanks and if anything is unclear or I used the wrong word for something, please tell me.
Edit:
It should make something like this:
if (k.getStatus().equals("completed"){
String s = "completed ones \n"
s += k.toString() + ".\n"; //get all completed ones
}
if (k.getStatus().equals("uncompleted"){
String s = "uncompleted ones \n"
s += k.toString() + ".\n"; //get all uncompleted ones
}
Simply add the condition inside the for() loop:
for (Klus k : alleKlussen) {
if (k.getStatus().equals("completed")) {
s += k.toString() + ".\n";
}
}
From the additional information in the question, it seems like the following is what is intended:
String completed = "completed ones \n";
String uncompleted = "uncompleted ones \n";
for (Klus k : alleKlussen) {
if (k.getStatus().equals("completed")) {
completed += k.toString() + ".\n"; //get all completed ones
}
else if (k.getStatus().equals("uncompleted")) {
uncompleted += k.toString() + ".\n"; //get all uncompleted ones
}
}
You should also consider using a StringBuilder to create the result strings, which reduces the memory overhead.
You can use switch if you have many conditions and it is easy to read
for (Klus k : alleKlussen)
{
switch(k.getStatus()){
case "completed": ....
break;
case "uncompleted": ....
break;
default: ...
}
}
Please note switch with String literals is only supported in Java 7.
Use this - this toString will print only Klus are completed.
public String toString()
{
String s = "text.\n";
for (Klus k : alleKlussen)
{
if("completed".equals(k.getStatus ()))
s += k.toString() + ".\n";
}
return s;
}
Why not just do the standard if-conditionals, such as:
if ("".equals(k.getStatus())) {
} else if ("completed".equals(k.getStatus())) {
}
To append the uncompleted after the completed ones, try this (And I suggest using enums, but you are welcome to stick to Strings. But then this will only work in Java SE 7!):
State.java:
// Makes switches easy to use and String typos are impossible
public enum State { COMPLETE, INCOMPLETE };
Replace your current String "state" with the enum like so:
Klus:java
public class Klus {
private State state;
...
public State getState() { return this.state; }
...
}
Now use it in a switch in the for loop. Use two strings, one for complete, one for incomplete. Append them in the end. (Note the use of StringBuilder instead of str +=... )
Class containing your toString():
public String toString() {
StringBuilder complete = new StringBuilder("completed ones \n"),
uncompleted = new StringBuilder("uncompleted ones \n");
for(Klus k : alleKlussen) {
switch(k.getStatus())
case COMPLETE:
complete.append(k.toString()).append(".\n"); break;
case INCOMPLETE:
uncompleted.append(k.toString()).append(".\n"); break;
default:
}
}
complete.append(uncompleted.toString();
return complete.toString();
}
Can Any help me and Check my answer
(a) Declare a private instance variable (Attribute) called HouseMap which should hold an unsorted map with integer keys and string values.
Private Map< Integer, String> HouseMap = new HashMap<Integer, String>();
(b) Write a zero-argument constructor of HouseCatalogue that initializes HouseMap to an empty map.
houseMap = new HashMap<Integer, String>();
(c) Write an instance method called addHouse() for the HouseCatalogue class that takes no arguments, and returns no value. This method should simply enter the four entries shown above into the HouseMap.
Public void addHouse()
{
HouseMap.put(101," adison Sas") ;
HouseMap.put(103," FourSeasons") ;
HouseMap.put(105," Hayat Regency ");
HouseMap.put(107," Concord al-Salam ") ;
}
(d) Write an instance method called printHouse() for the HouseCatalogue class that takes an integer argument, and return a string value. This method should print the value (House name) of the area code that is equal to integer argument and return it. Otherwise it will return null.
Public string printHouse( int area)
{
for(Integer eachcode : HouseMap.keySet())
{
if ( HouseMap.keySet()== area)
{
System.out.println("House name is"+ HouseMap.get(eachcode));
}
}
}
or
public static void printHouse( int area)
{
for(Map.Entry<Integer,String> entry : houseMap.entrySet())
{
if (entry.getKey().equals(area))
{
System.out.println("House name is"+ entry.getValue());
//return entry.getValue(); // return it
}
}
}
(a) Lower case letter for private and no new HashMap() needed when declaring. Normally when useing java convensions you use camelcase when declaring your variasbles (houseMap) but it's fine.
private Map<Integer, String> HouseMap;
(b) You have declared your variable with HouseMap not houseMap (see (a) camelcase) so initializing it needs the same variable:
HouseMap = new HashMap<Integer, String>();
(c) Seems fine
(d) Hum, don't see the point in the method, it should both print the value and return it.. well.. first off public lower case letters again, String with a big letter (name of the class` and then the implementation:
public String printHouse(int area) {
if (HouseMap.containsKey(area)) {
String name = HouseMap.get(area);
System.out.println("The house with the area code " + area +
" is " + name));
return name;
}
return null;
}
a) only declare the variable - do not initialize it
b) ok
c) ok
d) in a map you have random access. look at Map#get(Integer) API. you don't need to iterate over the entry set
Since the key of a map is unique, you can simplify the last method as follows:
public static void printHouse( int area)
{
String name = houseMap.get(area); // May return null
System.out.println("House name is " + name);
return name;
}
public and private must be written with a lowercase p everywhere.
You should show the entire constructor, not just the code that goes in it.
Fix your indentation. Use the same amount of indentation for every level, and make sure that everything lines up neatly.
When you use a foreach loop like for (Integer eachcode: HouseMap.keySet()), the iteration variable is eachcode. This is the value that you should compare to area, because that's what the integer is. You don't want to compare the supplied to all of the area codes taken as a single unit (those aren't the same kind of thing); you want to compare it to each area code in turn.
But you don't want to write that loop at all. The point of a HashMap is to let you look up the value, given the key. That is what .get() does. You have the key: it is area. So all you need to do is look it up: System.out.println("House name is " + HouseMap.get(area)).
You also need to return the name that you looked up, not just print it, and you need to check that the name is there (use .contains()) before printing.
It looks like somebody else commented your code to say "you also forgot to return it". Did you try talking to this person, or reading the comments?
Just a hint for the last one:
(d) Write an instance method called
An instance method is not a static method, you have to remove the static keyword in your second (d) method...
Thanks alot for every body
public static String printHouse(int
code) {
if (houseMap.containsKey(code))
{
String name = houseMap.get(coe);
System.out.println(code+ " : " + name);
return name;
} else{
System.out.println("null");
return null; }