• 0

what am I doing wrong?


Question

As an output, "Player card" should be outputted with randomly selected suit and value, but it's not.

Is there something missing or I have my if...else statements messed up? I know I can use do...while, but it's not required.


public static void main(String[] args){

//A new object, player card for the card suit.
Card player = new Card();

//Setting the suit for player card to be displayed randomly
player.setSuit((int) (Math.random()*4));

//Setting the value for player card to be displayed randomly
player.setValue(1 + (int)(Math.random()*12));
//A new object, computer card for the card suit
Card comp = new Card();

//Setting the suit for computer card to be displayed randomly
comp.setSuit((int) (Math.random()*4));

//Setting the value for computer card to be displayed randomly
comp.setValue(1 + (int)(Math.random()*12));


if((comp.getValue()== player.getValue()) && (comp.getSuit() == player.getSuit()))
System.out.println("Player Card: " + player.getValueString() + " of " + player.getSuitString());
System.out.println("Computer Card: " + comp.getValueString() + " of " + comp.getSuitString());
if(player.getValue() > comp.getValue())
System.out.println("Player won!");
else if(player.getValue() < comp.getValue())
System.out.println("Computer won!");
else
System.out.println("Tie!");
[/CODE]

Link to comment
https://www.neowin.net/forum/topic/1063892-what-am-i-doing-wrong/
Share on other sites

12 answers to this question

Recommended Posts

  • 0

You're missing curly brackets around the body of your if statements. The indentation suggests something else than what is actually happening.

if (...)
// statement 1
// statement 2[/CODE]

is not equivalent to

[CODE]if (...) {
// statement 1
// statement 2
}[/CODE]

In the former case, statement 2 is actually outside the body of the if, so it always executes.

It's good practice to always use curly brackets in this case, as well as for loops, while loops, etc. I never omit them precisely because I've seen this mistake crop up too often, even in code written by professionals.

Also I'm puzzled by your first condition: that the computer card equals the player card. You're aware that you're producing different numbers for the computer card and player card, right? They will only be equal once in a while (rarely at that), not by necessity.

  • 0

This is what I have so far, this should look a little better:


//Output the results of selected cards and suits for the Player and the Computer
System.out.println("Player Card: " + player.getValueString() + " of " + player.getSuitString());
System.out.println("Computer Card: " + comp.getValueString() + " of " + comp.getSuitString());

//Indicating if the results of the player and computer are equal or not
if((comp.getValue() == player.getValue()) && (comp.getSuit() == player.getSuit())){
System.out.println("Tie!");
}

//Indicating the results of values selected
if(player.getValue() > comp.getValue()){
System.out.println("Player won!");
}
else
//Indicating the results values selected
if(player.getValue() < comp.getValue()){
System.out.println("Computer won!");
}
[/CODE]

  • 0

This part of the code I have:


//Displaying constants of the 4 suits of cards.
public final static int SPADES = 0,
HEARTS = 1,
DIAMONDS = 2,
CLUBS = 3;


//Displaying the name of the suits.
//If the name is invalid, it returns as "invalid".
public String getSuitString() {
switch (suit) {
case SPADES: return "Spades";
case HEARTS: return "Hearts";
case DIAMONDS: return "Diamonds";
case CLUBS: return "Clubs";
default: return "invalid";
}
}
[/CODE]

But it results in error.

I know it has do with the line of code SPADES, where I've assigned a value 0, which is not correct?

Also, it's not recommended to using String variables with switch statements? I should replace it with if statements?

  • 0

This part of the code I have:


//Displaying constants of the 4 suits of cards.
public final static int SPADES = 0,
HEARTS = 1,
DIAMONDS = 2,
CLUBS = 3;


//Displaying the name of the suits.
//If the name is invalid, it returns as "invalid".
public String getSuitString() {
switch (suit) {
case SPADES: return "Spades";
case HEARTS: return "Hearts";
case DIAMONDS: return "Diamonds";
case CLUBS: return "Clubs";
default: return "invalid";
}
}
[/CODE]

But it results in error.

I know it has do with the line of code SPADES, where I've assigned a value 0, which is not correct?

Also, it's not recommended to using String variables with switch statements? I should replace it with if statements?

Where are you defining suit? The error may be showing on the second line of the switch, but it could be a problem with the first line.

  • 0

Here's my entire code:


public class Card {
//Displaying constants of the 4 suits of cards.
public final static String SPADES = 0,
HEARTS = 1,
DIAMONDS = 2,
CLUBS = 3;

//Displaying constants of types of cards in the card deck.
public final static int ACE = 1,
JACK = 11,
QUEEN = 12,
KING = 13;

//Identifies the suit of the card.
//Could be any of the 4: Spades, Hearts, Diamonds, or Clubs
private String suit;

//Identifies the value of the card.
//They are numbered from 1 to 13.
private int value;

//Identifies the rank of the card
private String rank;

/**
* Description of setSuit(int theSuit)
* @param theSuit
* The suit value to set for the card
*/
//The set method for the card suit.
public void setSuit(String s) {
suit = s;
}

/**
* Description of setValue(int theValue)
* @param theValue
* The value to set for the card
*/

public String getRank(){
return rank;
}

//The set method for the card values
//The range of the value is from 1 to 13
public void setValue(int v) {

if(value >= 1 && value <= 13)
value = v;
else
value = 1;
if(value == 1)
rank = "Ace";
else
if(value == 11)
rank = "Jack";
else
if(value == 12)
rank = "Queen";
else
if(value == 13)
rank = "King";
else
rank = Integer.toString(value);

}

//The get method for the card suit.
public String getSuit() {
return suit;
}

//The get method for the card values.
public int getValue() {
return value;
}

//Displaying the name of the suits.
//If the name is invalid, it returns as "invalid".




public String getSuitString() {
switch (suit) {
case SPADES: return "Spades";
case HEARTS: return "Hearts";
case DIAMONDS: return "Diamonds";
case CLUBS: return "Clubs";
default: return "invalid";
}
}

//Displaying the value of each card.
//If the value is invalid, it returns as "invalid".
public String getValueString() {
switch (value) {
case 1: return "Ace";
case 2: return "2";
case 3: return "3";
case 4: return "4";
case 5: return "5";
case 6: return "6";
case 7: return "7";
case 8: return "8";
case 9: return "9";
case 10: return "10";
case 11: return "Jack";
case 12: return "Queen";
case 13: return "King";
default: return "invalid";
}
}
}//end class
[/CODE]

  • 0


public class Card {
//Displaying constants of the 4 suits of cards.
public final static String SPADES = 0,
HEARTS = 1,
DIAMONDS = 2,
CLUBS = 3;

//Identifies the suit of the card.
//Could be any of the 4: Spades, Hearts, Diamonds, or Clubs
private String suit;

/**
* Description of setSuit(int theSuit)
* @param theSuit
* The suit value to set for the card
*/
//The set method for the card suit.
public void setSuit(String s) {
suit = s;
}


//The get method for the card suit.
public String getSuit() {
return suit;
}


//Displaying the name of the suits.
//If the name is invalid, it returns as "invalid".
public String getSuitString() {
switch (suit) {
case SPADES: return "Spades";
case HEARTS: return "Hearts";
case DIAMONDS: return "Diamonds";
case CLUBS: return "Clubs";
default: return "invalid";
}
}
}//end class
[/CODE]

your problem is that fact that you are asigning 0 to a string. You can't do that. To fix your problem that you are seeing.

do:

[CODE]
//Displaying constants of the 4 suits of cards.
public final static String SPADES = "0",
HEARTS = "1",
DIAMONDS = "2",
CLUBS = "3";
[/CODE]

If you want to use integers, you will need to change all the "Suit" string to be integers, and do an Int32.Parse (or Convert.) whatever the keyword is. You need to remember: "0" != 0 and what you were trying to do was compare "0" and 0 which can't be compared.

  • 0

oh...that's it? :blush:

Can you guys look at this code, how is it?


public static void main(String[] args){

int playerValue;
int compValue;
int playerSuit;
int compSuit;

Card playerCard = new Card();
Card compCard = new Card();

playerValue = ((int) (Math.random() * 100));
compValue = ((int) (Math.random() * 100));

playerCard.setValue(playerValue);
compCard.setValue(compValue);
playerValue = ((int)(Math.random() * 100));
compValue = ((int)(Math.random() * 100));

if(playerValue == compValue && playerSuit == compSuit){
compSuit = compSuit + 1;
if(compSuit > 4)
compSuit = 1;
}
if(playerSuit == 1)
playerCard.setSuit("Spades");
else
if(playerSuit == 2)
playerCard.setSuit("Hearts");
else
if(playerSuit == 3)
playerCard.setSuit("Diamonds");
else
playerCard.setSuit("Clubs");

if(compSuit == 1)
compCard.setSuit("Spades");
else
if(compSuit == 2)
compCard.setSuit("Hearts");
else
if(compSuit == 3)
compCard.setSuit("Diamonds");
else
compCard.setSuit("Clubs");

System.out.println("Player card is " + playerCard.getRank() + " of " + playerCard.getSuit());
System.out.println("Computer card is " + compCard.getRank() + " of " + compCard.getSuit());

if(playerValue == compValue)
System.out.println("Tie!!");
else
if(playerValue > compValue)
System.out.println("Player wins!");
else
System.out.println("Computer wins!");
[/CODE]

  • 0

^^ You don't set anything for playerSuit nor compSuit anywhere... unless that's not all your code.

This is my other class, I've already declared playerSuit and ranks...


public class Card {
//Displaying constants of the 4 suits of cards.
public final static String SPADES = "0",
HEARTS = "1",
DIAMONDS = "2",
CLUBS = "3";

//Displaying constants of types of cards in the card deck.
public final static int ACE = 1,
JACK = 11,
QUEEN = 12,
KING = 13;

//Identifies the suit of the card.
//Could be any of the 4: Spades, Hearts, Diamonds, or Clubs
private String suit;

//Identifies the value of the card.
//They are numbered from 1 to 13.
private int value;

//Identifies the rank of the card
private String rank;

/**
* Description of setSuit(int theSuit)
* @param theSuit
* The suit value to set for the card
*/
//The set method for the card suit.
public void setSuit(String s) {
suit = s;
}

/**
* Description of setValue(int theValue)
* @param theValue
* The value to set for the card
*/

public String getRank(){
return rank;
}

//The set method for the card values
//The range of the value is from 1 to 13
public void setValue(int v) {

if(value >= 1 && value <= 13)
value = v;
else
value = 1;
if(value == 1)
rank = "Ace";
else
if(value == 11)
rank = "Jack";
else
if(value == 12)
rank = "Queen";
else
if(value == 13)
rank = "King";
else
rank = Integer.toString(value);

}

public String toString(){
String theCard;
String[] cardRank = {"Ace","Two","Three","Four","Five","Six","Seven", "Eight","Nine","Ten","Jack","Queen","King"};
String[] playerSuit = {"Clubs","Diamonds","Hearts","Spades"};

// cardSuit is not needed for War:
theCard = (cardRank[rank]);
return theCard;
}

//The get method for the card suit.
public String getSuit() {
return suit;
}

//The get method for the card values.
public int getValue() {
return value;
}

//Displaying the name of the suits.
//If the name is invalid, it returns as "invalid".
public String getSuitString() {
switch (suit) {
case SPADES: return "Spades";
case HEARTS: return "Hearts";
case DIAMONDS: return "Diamonds";
case CLUBS: return "Clubs";
default: return "invalid";
}
}

//Displaying the value of each card.
//If the value is invalid, it returns as "invalid".
public String getValueString() {
switch (value) {
case 1: return "Ace";
case 2: return "2";
case 3: return "3";
case 4: return "4";
case 5: return "5";
case 6: return "6";
case 7: return "7";
case 8: return "8";
case 9: return "9";
case 10: return "10";
case 11: return "Jack";
case 12: return "Queen";
case 13: return "King";
default: return "invalid";
}
}
}//end class
[/CODE]

This topic is now closed to further replies.
  • Posts

    • BleachBit 6.0.1 Beta by Razvan Serea When your computer is getting full, BleachBit quickly frees disk space. When your information is only your business, BleachBit guards your privacy. With BleachBit you can free cache, delete cookies, clear Internet history, shred temporary files, delete logs, and discard junk you didn't know was there. Designed for Linux and Windows systems, it wipes clean thousands of applications including Firefox, Microsoft Edge, Google Chrome, Opera, Safari, and more. Beyond simply deleting files, BleachBit includes advanced features such as shredding files to prevent recovery, wiping free disk space to hide traces of files deleted by other applications, and vacuuming Firefox to make it faster. Better than free, BleachBit is open source. BleachBit has many useful features: Delete your private files so completely that "even God can't read them" according to South Carolina Representative Trey Gowdy. Simple operation: read the descriptions, check the boxes you want, click preview, and click delete. Multi-platform: Linux and Windows Free of charge and no money trail Free to share, learn, and modify (open source) No adware, spyware, malware, browser toolbars, or "value-added software" Translated to 64 languages besides American English Shred files to hide their contents and prevent data recovery Shred any file (such as a spreadsheet on your desktop) Overwrite free disk space to hide previously deleted files Portable app for Windows: run without installation Command line interface for scripting and automation CleanerML allows anyone to write a new cleaner using XML Automatically import and update winapp2.ini cleaner files (a separate download) giving Windows users access to 2500+ additional cleaners Frequent software updates with new features Going beyond standard deletion of files, BleachBit has several advanced cleaners: Clear the memory and swap on Linux Delete broken shortcuts on Linux Delete the Firefox URL history without deleting the whole file—with optional shredding Delete Linux localizations: delete languages you don't use. More powerful than localepurge and available on more Linux distributions. Clean APT for Debian, Ubuntu, Kubuntu, Xubuntu, and Linux Mint Find widely-scattered junk such as Thumbs.db and .DS_Store files. Execute yum clean for CentOS, Fedora, and Red Hat to remove cached package data Delete Windows registry keys—often where MRU (most recently used) lists are stored Delete the OpenOffice.org recent documents list without deleting the whole Common.xcu file Overwrite free disk space to hide previously files Vacuum Firefox, Google Chrome, Liferea, Thunderbird, and Yum databases: shrink files without removing data to save space and improve speed Surgically remove private information from .ini and JSON configuration files and SQLite3 databases without deleting the whole file Overwrite data in SQLite3 before deleting it to prevent recovery (optional) BleachBit 6.0.1 Beta release notes: BleachBit 6.0.1 beta is now available for testing. This maintenance-focused release includes bug fixes, updated translations, and a range of safe enhancements. This release fixes a Windows security issue that could allow arbitrary file deletion during privileged cleaning (reported by Zeze with TeamT5). It also adds new cleaners (including a DNS cache cleaner, Claude Code, and Visual Studio Code forks), support for multiple Chrome and Edge profiles, new deep scan options for developer directories like node_modules and venv, and safer, faster file shredding. All Platforms Added cleaners for Claude Code, DNS cache, and many Visual Studio Code forks. Added support for multiple Chrome and Edge profiles. Chrome can now clean downloaded AI models. Deep Scan can optionally remove venv, __pycache__, node_modules, and .angular directories. Deep Scan is faster by skipping directories on the keep list. File shredding is safer, faster, and leaves fewer recoverable traces. Improved handling of cookies, symlinks, Unicode filenames, external processes, and configuration files. Improved Expert Mode warnings and long warning dialogs. Fixed crashes related to cleaner detection, invalid Unicode, and malformed cleaner data. Clipboard is now cleared automatically after shredding files via paste operations. Linux Added AppImage support. Added cleaners for Visual Studio Code, Codeium, Librewolf (.deb), Transmission (Flatpak), and Profanity. Improved Linux trash detection, including Snap-installed applications and mounted drives. Fixed Wayland root CLI issues and several Snap-related problems. Improved package dependencies, AppStream metadata, and desktop file handling. Fixed startup crashes when Python Requests is unavailable. Windows Fixed a security vulnerability that could allow arbitrary file deletion when cleaning with elevated privileges. Added %WindowsSystem% variable support. Improved clipboard clearing using native Windows APIs. Improved installer experience on unsupported Windows versions. Reduced installer size and improved application robustness. Fixed Unicode handling, filename anonymization, Git revision reporting, and splash screen stability. [full release notes] Download: BleachBit 6.0 | Portable | ~20.0 MB (Open Source) View: BleachBit Home page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • DriversCloud 12.1.6 by Razvan Serea With DriversCloud (formerly My-Config.com), you can explore your computer easily, safely and free. The application quickly scans your PC and identifies the hardware and software components. DriversCloud then establishes a list of the different drivers compatible with your OS and hardware. Download the drivers needed for the proper functioning of your computer. To detect your drivers, DriversCloud also displays a detailed summary of your hardware and software configuration, analyzes your BSOD, monitors in real-time your PC voltages and temperatures and lets you share your configuration online. Once the hardware components have been detected, you will be able to obtain with just a few clicks the latest drivers corresponding to the identified hardware. You can record your configuration on the site for free, and can get the corresponding URL to post the configuration to technical forums, e-mail and social networks. You can also download the detection result (the configuration) as a PDF file. To protect the user's privacy and data confidentiality, a 4-level confidentiality system was created that filters the XML marks and gives control to the user. The default level can be modified in the preferences. Using the maximum level will prevent the user from publishing his configuration and generating a corresponding PDF file. In non-connected mode, each XML configuration is stored on the server for one day (for practical reasons). However, you are given the opportunity to manually delete it. Created in 2004, and continually improved, My-Config.com has established itself on the web as a free service to PC users running Windows and Linux operating systems. The service is designed to work with the most common Internet browsers (Edge, Firefox, Chrome, Safari). Download: DriversCloud 64-bit | 20.0 MB (Freeware) Download: DriversCloud 32-bit | 18.9 MB Link: DriversCloud Home Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • One Month Later
      AndreaB earned a badge
      One Month Later
    • One Month Later
      agatameier earned a badge
      One Month Later
    • Week One Done
      agatameier earned a badge
      Week One Done
    • Week One Done
      ssd21345 earned a badge
      Week One Done
    • Contributor
      MarkHughes4096 went up a rank
      Contributor
  • Popular Contributors

    1. 1
      +primortal
      516
    2. 2
      +Edouard
      189
    3. 3
      PsYcHoKiLLa
      148
    4. 4
      ATLien_0
      96
    5. 5
      Steven P.
      76
  • Tell a friend

    Love Neowin? Tell a friend!