• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Ron McLeod
  • Tim Cooke
Sheriffs:
  • Devaka Cooray
  • paul wheaton
  • Mark Herschberg
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Frits Walraven
  • Jj Roberts
Bartenders:
  • Carey Brown
  • salvin francis
  • Piet Souris

Java - Loop through instances of a class

 
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have 3 instances of a book class, two hard coded and one that will book to a list via user input, What is the best way to iterate through different instances of a class
 
Bartender
Posts: 7788
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Use an enhanced for() loop.

 
Carey Brown
Bartender
Posts: 7788
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's not clear why UserInput has-a collection of Books.
 
Carey Brown
Bartender
Posts: 7788
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The use of scan.next() on lines 4, 11, and 17 should probably be replaced by scan.nextLine(). You want to be able to include spaces and you want to capture every thing type until the Enter key is pressed. In the case of ISBN you may need additional logic to reject ill formed ISBN numbers.

On line 14 you have an int that receives its value from checkInput(). The name "checkInput()" does not describe the kind of task that we expect an int back from. A better name should be used that describes what the method does.

Lines  24 and 25 are going to be called each time around the while() loop, thus adding the books from lines 21 and 22 multiple times. What will your code do if the same Book is entered more than once?
 
Marshal
Posts: 26381
81
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Carey Brown wrote:It's not clear why UserInput has-a collection of Books.



Nor why this collection of Books is named "book".
 
Marshal
Posts: 72059
312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Carey Brown wrote:The use of scan.next() on lines 4, 11, and 17 should probably be replaced by scan.nextLine(). . . .

Agree; there is however a problem. It is likely that the call in line 17 is preceded by nextInt(). In which case there is a risk of nextLine() returning an empty String. If this happens, your inputs will be thrown out of sequence; there is more explanation and a possible solution in this old post. Creating an input utility class would be a much more time‑consuming solution, but I prefer it. Such a class would allow you not to write multiple dot operators (see line 11).

. . . additional logic to reject ill formed ISBN numbers.

The ISBNs shown are indeed ill‑formed. It would be better to create an ISBN class and make it immutable and do the validation in its constructor than to try using plain Strings.
 
Kevin O'Sullivan
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for replies, I was trying to spilt everything into classes, I'll just post all the code up, maybe ye can give me some pointers, just on the nextline thing carey mentioned , I was having trouble with that in that it would skip the next line so changed it to next(); and that worked but I make any spaces then then I tried putting next(); after it and that didn't work either, also how come it won't let me print out the list of books hardcoded into but If insert one book in via user input and then choose display all book option it will display them all ?









 
Master Rancher
Posts: 4188
38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can you copy the contents of the command prompt window that shows the problems you are talking about?
Be sure to add some comments to the output to show where the output wasn't expected.
For example:
 <<<< This should be ....
 
Kevin O'Sullivan
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Norm Radder wrote:Can you copy the contents of the command prompt window that shows the problems you are talking about?
Be sure to add some comments to the output to show where the output wasn't expected.
For example:
 <<<< This should be ....



No problem I'll do it tomorrow as it bedtime now .
 
Carey Brown
Bartender
Posts: 7788
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"AddBook" is a verb phrase, it describes an action not an object. Objects have data and behaviors. A library has Books (data) and can add-a-book (behavior). Your UserInput class has some static methods that would be appropriate for a utility class but as such it should not have knowledge of how it's being used by the next layer up. For instance, if you have a Library class with Books that may make several calls to your UserInput class, such as getMenuChoice(). In UserInput the getMenuChoice() method should not know or care about how the choice value to be returned is to be used. So the switch() more rightly belongs in the Library layer.

See my signature below, it has a link to a KeyboardUtility class. You could use it as is, copy it and hack away at it till it has only what you need, or get some ideas from it (or ignore it). The problem you mentioned about missing inputs when you changed to nextLine() is addressed in that wrapper class.

The long explanation of your missing data problem is that nextInt() will leave a new-line pending in the input queue. Then when you call nextLine() the first thing it sees is the new-line and thinks that the input is complete resulting in an empty string. There are two ways to fix this: 1) don't use nextInt(), use nextLine() for everything (this is the way my utility was written), or 2) flush the new-line after nextInt() by a separate call to nextLine() that just throws the empty string away. Example:
This holds true for all the nextXXX() methods except nextLine().
 
Carey Brown
Bartender
Posts: 7788
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
Campbell Ritchie
Marshal
Posts: 72059
312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I used to handle nextLine() like that but since I wrote my utility class I have taken a different approach, with a loop, something like this:-The message parameter would be something like, “Please enter address: ”. I took great delight in writing a while with a semicolon at the end because everybody knows you aren't supposed to do that
It keeps repeating until a non‑empty line is found. The strip() method was intoduced about Java11 to remove leading and trailing whitespace; I prefer it to trim(). A Scanner allows you to anticipate an input: in this sort of interaction (user input underlined), nextInt()...nextLine() will interpret the input correctly:-

Enter number of toes:
93 742 Evergreen Terrace Springield
Enter address please:

Maybe I have very big feet.
 
Kevin O'Sullivan
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for all the replies, very helpful as always.

I have two books hardcoded into the library how come it won't print out that list of 2 books when I call the print() menthod ? but for some reason I have use the userinput to input one book and then it will display all 3 books, any ideas?




Here is the command prompt, when I press 4 a list of books should appear but as you can see nothing is showing



 
Norm Radder
Master Rancher
Posts: 4188
38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is there anything to print in the new instance of the AddBook class's print method?
Add a print statement to the print() method that prints out the size of the list that is to be printed.
 
Campbell Ritchie
Marshal
Posts: 72059
312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Also, please go through the case 4: code carefully and see what it actually does.
 
Kevin O'Sullivan
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Norm Radder wrote:Is there anything to print in the new instance of the AddBook class's print method?
Add a print statement to the print() method that prints out the size of the list that is to be printed.






Something like the above? it still didn't print anything.
 
Carey Brown
Bartender
Posts: 7788
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm guessing that this print method isn't even being called because it's not a method inside AddBook class.
 
Norm Radder
Master Rancher
Posts: 4188
38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

 it still didn't print anything.

If the list is empty, the loop won't iterate.  If the loop doesn't execute, the print statement won't be executed.  But you already knew that because nothing was printed.
Move it outside of the loop.
 
Kevin O'Sullivan
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Carey Brown wrote:I'm guessing that this print method isn't even being called because it's not a method inside AddBook class.




No it is in the AddBook class

 
Kevin O'Sullivan
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Norm Radder wrote:

 it still didn't print anything.

If the list is empty, the loop won't iterate.  If the loop doesn't execute, the print statement won't be executed.  But you already knew that because nothing was printed.
Move it outside of the loop.



Ok I see what you mean now, it printed zero which tells me the hardcoded books aren't even added to the list.
 
Norm Radder
Master Rancher
Posts: 4188
38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

books aren't even added to the list.

A first step.
Where are the books supposed to be added?  Why isn't that code being executed?
 
Kevin O'Sullivan
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Norm Radder wrote:

books aren't even added to the list.

A first step.
Where are the books supposed to be added?  Why isn't that code being executed?



Suppose to be added to the Book list in the UserInput class, I can't figure out why there not being added though, seeing as there being as added when prompted too .
 
Carey Brown
Bartender
Posts: 7788
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Could you please re-post ALL of the code again. I think the problem lies somewhere other than the snippets we're seeing.
 
Norm Radder
Master Rancher
Posts: 4188
38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Suppose to be added


Is that code being executed?  Add a print statement so you can see.
 
Kevin O'Sullivan
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Carey Brown wrote:Could you please re-post ALL of the code again. I think the problem lies somewhere other than the snippets we're seeing.



Sure thing, thanks for your help.













 
Kevin O'Sullivan
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Norm Radder wrote:

Suppose to be added


Is that code being executed?  Add a print statement so you can see.



Also thank you for you trying to help as well.

Sorry not sure what you mean, add a print statement where? in the userinput class ?
 
Norm Radder
Master Rancher
Posts: 4188
38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

add a print statement where?  


Add print statements in all the places where the code is supposed to be executed to load the list that is empty in the print method.
The print outs will show you where the code is being executed or not being executed if there isn't a print out.
 
Carey Brown
Bartender
Posts: 7788
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This was my run with your code:
 
Carey Brown
Bartender
Posts: 7788
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So, your code seems ok, then it is probably how it is being compiled. Make sure all .java files are saved. Remove all .class files. Do a complete re-compile. Try it again.
 
Kevin O'Sullivan
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Carey Brown wrote:So, your code seems ok, then it is probably how it is being compiled. Make sure all .java files are saved. Remove all .class files. Do a complete re-compile. Try it again.




Sorry carey I should have clarified, when you first enter the program and press 4 to see what books are already available , it doesn't show the hardcoded books until after you enter one and I just realised the reason might be because those hardcoded books should be somewhere else and not in that class.
 
Norm Radder
Master Rancher
Posts: 4188
38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

those hardcoded books should be somewhere else


Yes, that looks like the problem.  Do you have any ideas about where that code should go so its results are available anywhere else in the program's execution?
 
Kevin O'Sullivan
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Norm Radder wrote:

those hardcoded books should be somewhere else


Yes, that looks like the problem.  Do you have any ideas about where that code should go so its results are available anywhere else in the program's execution?



Would you put them in their own class prehaps ?
 
Carey Brown
Bartender
Posts: 7788
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm not sure that I like the way you've broken down your classes, but given what you have, I'd add an initLibrary() method to UserInput and call it from main().
 
Norm Radder
Master Rancher
Posts: 4188
38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Cary Brown wrote:I'm not sure that I like the way you've broken down your classes


I agree.  It's like the classes were randomly created and methods add to them.

One BIG flaw in the project is the use of static.  There should only be one method that is static: main.  There should not be any static fields.
 
Carey Brown
Bartender
Posts: 7788
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Generally speaking a class would appear in your requirements as a noun. Therefore "library" and "book" would be suitable classes whereas "AddBook" would not. "Add", "Search", and "Delete" are verbs describing an action and are generally implemented as methods.

As Norm pointed out you (mostly) shouldn't have any static methods in your project except if you are creating a utility class that has nothing but static methods.

Here is an example of your project using my utilities "Print2" and "Kbd2". "Print2" i'm including here, "Kbd2" is a truncated version of the "Keyboard" utility you can find a link to in my signature. See how much cleaner this is and easier to follow the flow of logic?

 
Kevin O'Sullivan
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for that example carey and for the explanation, the whole reason I made the UserInput class static was because I wanted to make it a utility class, I see now I got it completely wrong and will have to go back and check my understanding of utility classes.
 
Carey Brown
Bartender
Posts: 7788
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Utility Classes, a general guideline:
  • Made up entirely of static methods.
  • Have no knowledge of the application's business logic.
  • Make no calls to the application specific code.
  • Only makes calls to Java libraries or other utility classes.
  • Ideally written in a portable manner so that it would be portable to another application.

  • If you find yourself bending these rules then perhaps you really aren't dealing with a clean utility situation.
     
    Kevin O'Sullivan
    Ranch Hand
    Posts: 81
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Carey Brown wrote:Utility Classes, a general guideline:

  • Made up entirely of static methods.
  • Have no knowledge of the application's business logic.
  • Make no calls to the application specific code.
  • Only makes calls to Java libraries or other utility classes.
  • Ideally written in a portable manner so that it would be portable to another application.

  • If you find yourself bending these rules then perhaps you really aren't dealing with a clean utility situation.



    Would a login class that takes a user name and password be considered a good candidate for a utility class ?
     
    Carey Brown
    Bartender
    Posts: 7788
    70
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Kevin O'Sullivan wrote:Would a login class that takes a user name and password be considered a good candidate for a utility class ?


    Maybe.

  • Would it need to call any business logic?
  • Would it need to remember a state? That is, would it need its own member variables (a.k.a. fields)?
  • Would it need a constructor?
  •  
    Carey Brown
    Bartender
    Posts: 7788
    70
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Can you give me an example of what you're thinking with the methods stubbed out?
     
    Those who dance are thought mad by those who hear not the music. This tiny ad plays the bagpipes:
    the value of filler advertising in 2021
    https://coderanch.com/t/730886/filler-advertising
    reply
      Bookmark Topic Watch Topic
    • New Topic