• 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

    • DiskGenius 6.2.0.1829 - All Versions: Free, Lite & Portable by Razvan Serea DiskGenius is a full-featured partition manager, which is designed to optimize disk usage for Windows users. It will efficiently help you recover lost data, resize/split partition, backup files, edit hex data, check bad sectors, manage virtual disks, erase data, etc.. Create a system image backup for current Windows with simple clicks to keep the operating system under protection. DiskGenius key features: Partition Management - It can create format, resize, extend, backup, split, hide and clone partition, both MBR and GPT are supported. Disk and partition conversion - Convert dynamic disk to basic, convert virtual disk format and convert MBR to GPT, convert primary partition to logical. File recovery - It can recover files deleted or emptied form recycle bin, recover files from damaged partition or disk and recover files by file type and supports file preview and file filter. Partition recovery - It is the best partition recovery program in that it can recover files from damaged, corrupted and RAW partitions, search for lost partition and recover files from it, besides, it can fix partition table. RAID recovery - It can reconstruct Virtual RAID and recover files from it, and all RAID types are supported. Sector Editor - A Hex editor is embedded to help users edit raw hex data and recover data manually. Backup and Restore - It can backup and restore partition including system partition, hard disk and partition table. Bad Tracks - It can check and repair bad sectors for all storage devices; check hard disk S.M.A.R.T. information. Delete files permanently - It can delete files permanently so that they can't be recovered by any data recovery software. Virtual Disk - It supports virtual disks, including VMware, Virtual PC and Virtual Box. Create WinPE bootable disk and you can manage disk partition when system crashes or there is no operating system on your computer. Support FAT12/FAT16/FAt32/exFAT/NTFS/EXT2/EXT3/EXT4 file system format. DiskGenius 6.2.0.1829 changelog: Add the "Disk Speed Test" feature. Add the "Windows Boot Repair and Conversion" feature. Add the BMB21-2019 erase standard to the "Erase Sectors" feature. Add support for restoring an individual partition from a PMFX disk image file. Enhanced The "Verify Or Repair Bad Sectors/Blocks" feature displays disk read speed in the detection window during scanning. The "Quick Partition" dialog box allows users to quickly select the number of partitions by pressing the numeric keys 1, 2, 7, 8, or 9. The "Set Volume Name" dialog box supports selecting preset volume labels provided by the software. The "Copy Sectors" feature supports resuming copy tasks after modifying the number of skipped bad sectors. Add the "TRIM Optimization" option to the format dialog box. The "Clone Partition" and "Clone Disk" features perform TRIM optimization on target partitions or disks before cloning. Add support for Not Equal To search conditions (prefixed with "!") when searching hexadecimal data in the sector editor. Optimize the display of capacity values in the program interface to show two decimal places. Add a minimize button to dialogs that may require long processing time. Enhance support for the ReFS file system. Enhance support for newer HIF and MP4 formats when recovering files by type. Enhance support for the EXT4 file system. Enhance compatibility of the "File Recovery" feature with special data structures. Fixed Fixed the issue that the selected file system type automatically reverted to NTFS after changing it to exFAT or EXT4 in the "Quick Partition" dialog box. Fixed inaccurate Unicode string search results in the "Sector Editor" feature. Fixed the issue that exceptions might occur when adding multiple disks in the "Erase Sectors" feature. Fixed the issue that insufficient target disk space was incorrectly reported in some cases when cloning, backing up, or restoring disks. Fixed the issue that folder modification timestamps were not preserved when copying files from ReFS partitions. Fixed the issue that Excel-format reports generated by features such as file copying or bad sector checking could not be opened when the report contained more than one million rows. Fixed the issue that folders were not displayed in the exclude-folder dialog box when backing up partitions to image files. Fixed the issue that the "Erase Sectors" feature could not be executed in some cases. Download: DiskGenius 6.2.0.1829 | 63.9 MB (Freeware, paid upgrade available) Download: DiskGenius Portable 64-bit | 40.0 MB Download: DiskGenius Portable 32-bit | 36.0 MB Download: DiskGenius Lite 64-bit | 13.4 MB Download: DiskGenius Lite 32-bit | 11.6 MB View: DiskGenius Home Page | DiskGenius Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Really? Use a better search engine https://www.google.com/search?...ourceid=chrome&ie=UTF-8
    • Seems like Neowin has transitioned into being simps for the white house. I can't find a review for the last UFC games that came out.
  • Recent Achievements

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

    1. 1
      +primortal
      513
    2. 2
      +Edouard
      182
    3. 3
      PsYcHoKiLLa
      143
    4. 4
      ATLien_0
      95
    5. 5
      Steven P.
      74
  • Tell a friend

    Love Neowin? Tell a friend!