• 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
  • Bear Bibeault
  • Liutauras Vilda
  • Devaka Cooray
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Tim Holloway
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

struggling with extra card being printed in beginner java exercise

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello! And a massive thank in advance for any help!

I've been banging my head against this for quite a while now. I'm trying to figure out why the output for this testdriver I created for this card class keeps showing an extra card. I need it to print five random cards (which it does), and then four more random cards and one invalid, which it also does, but it adds one more random card at the end which shouldn't be there. Just learning so all help so appreciated.

Here is the code I've written so far with the Card class at the top and the TestDriver at the bottom.

 
Sheriff
Posts: 6801
182
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your program isn't printing an extra card, it's printing the default card you set after you print after the warning.
What you want is a way to stop the creation of the Card if it's invalid.  You do this by throwing an exception.  Do you know how to do that?  Give it a try.
 
Sheriff
Posts: 14990
250
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To clarify what Knute said, on line 124 you're invoking the Card constructor on line 16. Because the parameters are invalid, line 19 is executed which displays the "Invalid" message. However, as Knute said, the Card is created anyway with a face and suit of 1. When line 125 is executed, it causes line 97 to be executed thus printing your "extra" card, the Ace of Clubs.
 
Alida Thomas
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This helps so much, thank you. We haven't learned how to throw exceptions yet, but looking it up now.
 
Hot dog! An advertiser loves us THIS much:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!