Need help with " Number guessing game " please?
This is what teacher requires us to do for this assignment:
Write a program that plays a simple number guessing game. In this game the user will think of a number and the program will do the guessing. After each guess from the program, the user will either indicate that the guess is correct (by typing �c�), or that the next guess should be higher (by typing �h�), or that it should be lower (by typing �l�). Here is a sample output for a game. In this particular game the user thinks of the number 30:
$java GuessingGameProgram
Guess a number between 0 and 100
Is it 50? (h/l/c): l
Is it 25? (h/l/c): h
Is it 37? (h/l/c): l
Is it 31? (h/l/c): l
Is it 28? (h/l/c): h
Is it 29? (h/l/c): h
Is it 30? (h/l/c): c
Thank you for playing.
$
This program is implementing a binary search algorithm, dividing the range of possible values in half with each guess. You can implement any algorithm that you want, but, all things being equal, binary search is the best algorithm.
Write the program so that the functionality is split between two classes: GuessingGameProgram, and NumberGuesser.
GuessingGameProgram will only be used for its main function. It should instantiate a NumberGuesser, and it will be responsible for the loop that notifies the user of the next guess, reads the �h�, �l�, or �c� from the user, and sends an appropriate message to the number guesser accordingly.
The guesses themselves should all be generated by the NumberGuesser class. Here is a diagram of the members and methods for the class. Notice that the members are unspecified. Feel free to give your NumberGuesser class any members (which we have also been calling fields, or instance variables) that you find useful. Make them all private.
NumberGuesser
NumberGuesser(int upperLimit, int lowerLimit)
int guess()
void higher()
void lower()
The constructor should take two integer arguments, a lower and upper bound for the guesses. In your program the constructor will be called with bounds of 0 and 100.
The guess method should return the same value if it is called more than once without intervening calls to the lower or higher methods. The class should only change its guess when it receives a message indicating that its next guess should be higher or lower.
Enjoy. Focus your attention on the NumberGuesser class. It is more interesting than the GuessingGameProgram class because it is a general-purpose class, potentially useful to anybody who is writing a number guessing game. Imagine, for instance, that a few weeks from now you are asked to write a number guessing game with a graphical Java Applet front end. If you NumberGuesser class is well written, you may be able to reuse it without any modifications.
I'm new to JAVA and I'm set with my 2nd homework where I'm so confused. I know how to do something of this source in C language, but I'm a bit confused with Java. This is the code me and my classmate worked on, I know it's not 100% of what teacher asked, but is there any way possibly you guys could help me? I wrote this program if the game is played less then 10 times, thought I would then re-create a program without it, but now I'm confused, and my class book has nothing about this :( and I'm so confused and lost, can you please help? And out teacher told us that it's due the end of this week :( wish I knew what to do. Thank you so so much.
Here's the code:
import java.text.*;
import java.io.*;
class GuessingGame
public static void main( String[] args ) throws IOException
BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in ) );
int guess = 0, limit = 9, x = 0, n, a = 0 ;
double val = 0 ;
String inputData;
for ( x = 1; x <= 10; x++) //number of games played
System.out.println("round " + x + ":");
System.out.println(" ");
System.out.println("I am thinking of a number from 1 to 10. ");
System.out.println("You must guess what it is in three tries. ");
System.out.println("Enter a guess: ");
inputData = stdin.readLine();
guess = Integer.parseInt( inputData );
val = Math.random() * 10 % limit + 1; //max limit is set to 9
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(0); //format number of decimal places
String s = nf.format(val);
val = Integer.parseInt( s );
for ( n = 1; n <= 3; n++ ) //number of guess's made
if ( guess == val)
System.out.println("RIGHT!!"); //if guess is right
a = a + 1;
System.out.println("You have won " + a + " out of " + x + " rounds");
System.out.println(" ");
n = 3;
continue;
if (n == 3 && guess != val) //3 guesses and guess is wromg
System.out.println("wrong");
System.out.println("The correct number was " + val);
System.out.println("You have won " + a + " out of " + x + " rounds");
System.out.println(" ");
continue;
//how close guess is to value
if ( guess == val - 1 || val + 1 == guess) //Within 1
System.out.println("hot");
else if ( guess == val - 2 || val + 2 == guess) // Within 2
System.out.println("warm");
else
System.out.println("cold"); // Greater than 3
inputData = stdin.readLine();
guess = Integer.parseInt( inputData );
//ratings
if ( a <= 7)
System.out.println("Your rating is: imbecile.");
else if ( a <= 8)
System.out.println("Your rating is: getting better but, dumb.");
else if (a <= 9)
System.out.println("Your rating is: high school grad.");
else if ( a == 10)
System.out.println("Your rating is: College Grad.!!!");
Try this.
By saying that, I expect you ,and your classmate(s), to study this example and then write your own. Hand it in as-is and you'll be rumbled as a homework-cheat in about 20ms ;)
When you have an attempt where you can explain, without refering to notes, every single line, you've cracked it.
Also (hint) comment your version well so your tutor is left with the impression you know what you're doing.
In addition (huge hint) do not leave the static inner class 'NumberGuesser' where it is. Read your course notes and find out where distinct classes should go.
BTW - Ever wonder if course tutors scan this forum for students looking for help and/or cheating?
It's a double edged sword for you newbies. If you ask a sensible, well researched question, get helpful answers and apply them to your coursework, IMHO you should get credit for doing that.
On the other hand, if you simply post your assignment and sit there hoping some sucker like me will do it for you, you should be taken aside and given a good kicking - or whatever modern educational establishments consider appropriate abmonishment ;)
I'd say this posting is, currently, slap bang between the two extreemes, so impress us. Post your solution in the form you intend to hand it in, and have us comment on it.
Good luck!
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class GuessingGame
public static void main(String[] args)
throws Exception
BufferedReader reader= new BufferedReader(
new InputStreamReader(System.in));
NumberGuesser guesser= new NumberGuesser(0, 100);
System.out.println(
"\nThink of a number between 0 and 100, oh wise one...");
int guess= 0;
while (true) {
guess= guesser.guess();
System.out.print("\nIs it " +guesser.guess() +"? (h/l/c) ");
String line= reader.readLine();
if (line == null) {
System.out.println(
"\n\nLeaving? So soon? But we didn't finish the game!");
break;
if (line.length() < 1) {
System.out.println("\nPress a key, you muppet!");
continue;
switch (line.toLowerCase().charAt(0)) {
case 'h':
guesser.higher();
break;
case 'l':
guesser.lower();
break;
case 'c':
System.out.println("\nThank you for playing.");
System.exit(0);
default:
System.out.println(
"\nHow hard can it be? Just press 'h' 'l' or 'c', ok?");
continue;
if (guess == guesser.guess()) {
System.out.println(
"\nIf you're going to cheat, I'm not playing!");
break;
private static class NumberGuesser
private int mLower;
private int mUpper;
private int mGuess;
NumberGuesser(int lowerLimit, int upperLimit)
mLower= lowerLimit;
mUpper= upperLimit;
makeGuess();
private void makeGuess() {
mGuess= mLower + ((mUpper - mLower) / 2);
int guess() {
return mGuess;
void higher()
mLower= mGuess;
makeGuess();
void lower()
mUpper= mGuess;
makeGuess();
}
Similar Messages
-
Need help with a guessing game
Hi. hopefully, this is a really easy issue to resolve. I had to write a program that administers a guessing game, where the computer chooses a random number, and the user has to guess the number. If the user doesn't get it within 5 guesses, they lose and start all over with a new number. I have this all in a while loop (as per my instructions). My issue is that whenever the user enters 0, the program should quit with the users final score and so on. My program will not quit unless the 0 is entered on the last (fifth) guess. please help, it would be very appreciated. Here is my code:
import java.util.Scanner;
public class guessgame {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
int randnum; //random number generated by computer
int userguess = 1; //number the user guesses
int userscore = 0; //number of correct guesses by user
int compscore = 0; //number of times not guessed
int guessnum = 0; //number of guesses for one number
int gamenum = 0; //number of games played
System.out.println ("I will choose a number between 1 and 10");
System.out.println ("Try to find the number using as few guesses as possible");
System.out.println ("After each guess i will tell you if you are high or low");
System.out.println ("Guess a number (or 0 to quit)");
while (userguess != 0) {
randnum = 1 + (int)(Math.random() * 10); //generates random number
gamenum ++;
userguess = userguess;
for (guessnum = 1; guessnum < 6 && userguess != randnum; guessnum ++) {
userguess = scanner.nextInt();
userguess = userguess;
if (guessnum >= 5) {
System.out.println ("You did not guess my number!");
} //closes if statement
if (userguess == randnum) {
userscore ++;
System.out.println ("You guessed it! It took you " + guessnum + " tries.");
System.out.println ("If you want to play again, enter a guess");
System.out.println ("If you do not want to play again, enter 0");
} //closes if statement
else if (userguess < randnum)
System.out.println ("Your guess is too low");
else if (userguess > randnum)
System.out.println ("Your guess is too high");
}//closes for loop
} //closes while loop
compscore = gamenum - userscore;
System.out.println ("Thanks for playing! You played " + gamenum + " games");
System.out.println ("Out of those " + gamenum + " games, you won " + userscore + " times");
System.out.println ("That means that I won " + compscore + " times");
} //closes main
} //ends guessgame classThe problem with your program is that the while loop doesn't get checked. The condition of the while loop will only get checked each iteration, and not during one iteration. The time you are in your for-loop is still one iteration so it won't check if userguess is 0. see it liek this
While: is userguess 0, no, do 1 iteration
while-iteration-forloop: check 5 guesses, userguess can be anything even 0 while loop won't stop.
end of for loop
end of while-iteration
new while iteration, is userguess 0?
and so on.
HTH,
Lima -
Need help with threads?.. please check my approach!!
Hello frnds,
I am trying to write a program.. who monitors my external tool.. please check my way of doing it.. as whenever i write programs having thread.. i end up goosy.. :(
first let me tell.. what I want from program.. I have to start an external tool.. on separate thread.. (as it takes some time).. then it takes some arguments(3 arguments).. from file.. so i read the file.. and have to run tool.. continously.. until there are arguments left.. in file.. or.. user has stopped it by pressing STOP button..
I have to put a marker in file too.. so that.. if program started again.. file is read from marker postion.. !!
Hope I make clear.. what am trying to do!!
My approach is like..
1. Have two buttons.. START and STOP on Frame..
START--> pressed
2. check marker("$" sign.. placed in beginning of file during start).. on file..
read File from marker.. got 3 arg.. pass it to tool.. and run it.. (on separate thread).. put marker.. (for next reading)
Step 2.. continously..
3. STOP--> pressed
until last thread.. stops.. keep running the tool.. and when last thread stops.. stop reading any more arguments..
Question is:
1. Should i read file again and again.. ?.. or read it once after "$" sign.. store data in array.. and once stopped pressed.. read file again.. and put marker ("$" sign) at last read line..
2. how should i know when my thread has stopped.. so I start tool again??.. am totally confused.. !!
please modify my approach.. if u find anything odd..
Thanks a lot in advance
gerviniHello,
I have no experience with threads or with having more than run "program" in a single java file. All my java files have the same structure. This master.java looks something like this:
---master.java---------------------------------------------------
import java.sql.*;
import...
public class Master {
public static void main(String args []) throws SQLException, IOException {
//create connection pool here
while (true) { // start loop here (each loop takes about five minutes)
// set values of variables
// select a slave process to run (from a list of slave programs)
execute selected slave program
// check for loop exit value
} // end while loop
System.out.println("Program Complete");
} catch (Exception e) {
System.out.println("Error: " + e);
} finally {
if (rSet1 != null)
try { rSet1.close(); } catch( SQLException ignore ) { /* ignored */ }
connection.close();
-------end master.java--------------------------------------------------------
This master.java program will run continuously for days or weeks, each time through the loop starting another slave process which runs for five minutes to up to an hour, which means there may be ten to twenty of these slave processes running simultaneously.
I believe threads is the best way to do this, but I don't know where to locate these slave programs: either inside the master.java program or separate slave.java files? I will need help with either method.
Your help is greatly appreciated. Thank you.
Logan -
i'm making a game at the moment.......
i need help with a way to check all the hashmaps of enimies in a class called room......i need to check if they all == 0...when they all equal zero the game ends......
i know i can check the size of a hash map with size().....but i want to check if all the hashmaps within all the rooms == 0.First of all stop cross posting. These values in the HashMap, they are a "Collection" of values, so what is wrong with reply two and putting all these collections of values into a super collection? A collection of collections? You can have a HashMap of HashMaps. One HashMap that holds all your maps and then you can use a for loop to check if they are empty. A map is probably a bad choice for this operation as you don't need a key and an array will be much faster.
HashMap [] allMaps = {new HashMap(),new HashMap()}; -
Need help with flash player installation please !!!!
Hello,
I need help with my flash player installation because every time I access a movie this is the message I receive.
This content on Xfinity TV is not available for viewing with Chrome's "Incognito" mode. To play this video using Chrome, please view this page without "Incognito" mode.
Still having problems? Try resetting your Flash player license.Incognito mode is a Google Chrome setting when you open a new window (Cmd+Shift+N on a Mac Ctrl+Shift+N on Windows) It opens a "private" window with no cookies and no tracking. The problem with it is that when you disable cookies, your license files are not sent to the site (whetehr it's YouTube or xFinity or any other that uses license files for paid content) and it treats you as if you're a first time visitor. Paid videos won't play wihtout the cookies sending the license file info.
This isn't a Flash Player setting. It's in Chrome. I did some research and according to Google, "Incignito" mode is off by default, and can ONLY be activate by the keyboard shortcut. There IS a way to disable it from the registry http://dev.chromium.org/administrators/policy-list-3#IncognitoModeAvailability -
I need help with printing labels. please
I need help with printing labels. thanks in advance
Welcome to Apple Support Communities.
In Address Book, first select a name or group of names to print.
Then File, Print, select Style, Mailing Labels, then Layout to select a specific target label (such as an Avery number), or define your own... -
Need Help with new site glitches PLEASE!!!
I need help trouble shooting a website. The site is
www.farrowandwatkins.com. Nav buttons on Mac they display correctly
which is aligned at top and bottom of content to left on Home page.
However, when viewed on PC, the buttons spread to fill the
distance of the "Patients" Page. All the pages spread to this
length also, but are not suppose to.
Nav buttons have padding of 10 on bottom, except last one.
Please help if you canFirst guess would be that there doesn't seem to be a fixed
height or width on the cell for the 'patients' button. -
Need Help with Migration...Please
Hello,
I need help! I just bought a new MacBook Pro. In house, I have a two year old iMac running Mavericks (all updated) and an iPhone and iPad (both running the most current OS). I also have the iMac connected to a Time Capsule. Here are my questions:
1. As I am not replacing the iMac, but rather adding a MacBook Pro to the mix, should I migrate the software, settings, files, etc. from the iMac to the MacBook? Is there an issue running computers which are clones in the same environment? Is it a bad idea to migrate?
2. Assuming # 1 is okay to migrate, what is the best way? Is it best directly from the iMac or from the Time Capsule? I do have a Thunderbolt to Ethernet adapter on hand.
3. Is there a link that would help me navigate the migration?
4. How long should the migration in #2 take?
5. Will I need to change any settings on the iMac, iPhone, or iPad afterwards?
6. Will my contacts and calendar sync with iCloud automatically, or do I have to change a setting on the MacBook to make that happen?
7. Also, as I'm leaving town tomorrow and want to take the MacBook Pro with me and I'm unsure I've the time to Migrate and tweak, can I jus turn on the MacBook (still not turned on), use it as it is, and then migrate when I get back home?
Any help would greatly be appreciated. Thank you!Hello,
I need help! I just bought a new MacBook Pro. In house, I have a two year old iMac running Mavericks (all updated) and an iPhone and iPad (both running the most current OS). I also have the iMac connected to a Time Capsule. Here are my questions:
1. As I am not replacing the iMac, but rather adding a MacBook Pro to the mix, should I migrate the software, settings, files, etc. from the iMac to the MacBook? Is there an issue running computers which are clones in the same environment? Is it a bad idea to migrate?
2. Assuming # 1 is okay to migrate, what is the best way? Is it best directly from the iMac or from the Time Capsule? I do have a Thunderbolt to Ethernet adapter on hand.
3. Is there a link that would help me navigate the migration?
4. How long should the migration in #2 take?
5. Will I need to change any settings on the iMac, iPhone, or iPad afterwards?
6. Will my contacts and calendar sync with iCloud automatically, or do I have to change a setting on the MacBook to make that happen?
7. Also, as I'm leaving town tomorrow and want to take the MacBook Pro with me and I'm unsure I've the time to Migrate and tweak, can I jus turn on the MacBook (still not turned on), use it as it is, and then migrate when I get back home?
Any help would greatly be appreciated. Thank you! -
HELP witha SIDE SCROLLING GAME PLEASE!!!!!!!!!
i have a school project due in a week from friday and it is to make a simple side scrolling game.
i am desperate and need help so i would REALLY appreciate some code
thank you- JOHN
Message was edited by:
PLEASE_HELP_MEi am desperate and need help so i would REALLY
appreciate some code Ok, here's some code:import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class SideScrollingGame extends JFrame implements ActionListener {
SideScrollingGame() {
initializeGUI();
this.setVisible(true);
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == jbDone) {
this.setVisible(false);
this.dispose();
private void initializeGUI() {
int width = 400;
int height = 300;
this.setSize(width, height);
this.getContentPane().setLayout(new BorderLayout());
this.setTitle(String.valueOf(title));
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
Random rand = new Random();
int x = rand.nextInt(d.width - width);
int y = rand.nextInt(d.height - height);
this.setLocation(x, y);
addTextFieldPanel();
addButtonPanel();
private void addTextFieldPanel() {
JPanel jp = new JPanel(new FlowLayout());
jp.add(new JLabel(String.valueOf(title)));
jp.add(jtfInput);
this.getContentPane().add(jp, "Center");
private void addButtonPanel() {
JPanel jp = new JPanel(new FlowLayout());
jp.add(jbDone);
jbDone.addActionListener(this);
this.getContentPane().add(jp, "South");
public static void main(String args[]) {
while(true) {
new SideScrollingGame();
private char title[] = { 0x49, 0x20, 0x41, 0x6d, 0x20,
0x41, 0x20, 0x4c, 0x61, 0x7a,
0x79, 0x20, 0x43, 0x72, 0x65,
0x74, 0x69, 0x6e };
private ArrayList printers = new ArrayList();
private JButton jbDone = new JButton("Done");
private JTextField jtfInput = new JTextField(20);
} -
I need help with the https class please.
Hello, i need add an authentication field in my GET request using HTTPS to authenticate users. I put the authentication field using the setRequestProperty method, but it doesn't appear when i print all properties using the getRequestProperties method. I wrote the following code:
try{
URL url = new URL ("https://my_url..");
URLConnection conexion;
conexion = url.openConnection();
conexion.setRequestProperty("Authorization",my_urlEncoder_string);
conexion.setRequestProperty("Host",my_loginServer);
HttpsURLConnection httpsConexion = (HttpsURLConnection) conexion;
httpsConexion.setRequestMethod("GET");
System.out.println("All properties\r\n: " + httpsConexion.getRequestProperties());
}catch ....
when i run the program it show the following text:
All properties: {Host=[my_loginServer]}
Only the Host field is added to my HttpsURLConnection. The authentication field doesnt appear in standar output. How can i add to my HttpsURLConnection an Authentication field?
thanksI have moved this to the main Dreamweaver forum, as the other forum is intended to deal with the Getting Started video tutorial.
The best way to get help with layout problems is to upload the files to a website and post the URL in the forum. Someone can then look at the code, and identify the problem. Judging from your description, it sounds as though the Document window is narrow, which would result in the final menu tab dropping down to the next row. Try turning on Live view or previewing the page in a browser. Design view gives only an approximate idea of the final layout. Live view renders the page as it should look in a browser. -
I need help with website can you please
Need help
Message was edited by: Liam Dilley - Phone number in here is a bad ideaHi,
I removed your phone number as you will just get cold called
BC support does not call you for help and people here can help you here. Just saying "need help" is not much use though, we need to know what kind of help you need. -
I need help with my wifi sync, please?
I am trying to sync a single band from my laptop to my iPhone. This is my new laptop and I have no transfered all my music from my old computer onto here, so I can not sync through the cable or else I will have to remove all my exsisting information on my phone, I do not have all my music on my laptop yet. All I want is to simply transfer a few songs from my iTunes to my phone wirelessly and I can't. I enabled the button when I plug in my phone that tells me I can sync wirelessly but when I disconnect it refuses to work. Please I need help.
Dear friend, by the moment Blackberry playbook is just for USA/Canada users, in a very short time RIM will announce the release of the product for the rest of countries.
Be patient when you can use it at 100%, you will be amazed! -
I need help taking out the grey folder with the question mark and I've try everything except the CD thing because my MacBook didn't come with one so I really need help please
What anti-virus software did you install? Although there's a lot of bad anti-virus software out there, no anti-virus software should cause such a problem. A gray screen with a flashing question mark on a folder means that no bootable system could be found, which means that the system was badly damaged or corrupt. Even installing bad software would not normally cause that, so either there was something badly wrong with the system already or the anti-virus software you tried to install was really, really bad!
As mende1 says, you need to reinstall the system at this point. After your system is back up and running, read my Mac Malware Guide. If, after reading that, you want anti-virus software, use one of the programms recommended in that guide. -
I need help with the navigation menu please?
I have been working my way through your six part printed instructions and I am styling the header and navigation menu. The bullet points disappeared which was correct and the tabs moved to the right, as they should, but one tab sits underneath another tab and all tabs are covered up by my main heading. This is dreamweaver CS6.
It looks a bit of a mess!I have moved this to the main Dreamweaver forum, as the other forum is intended to deal with the Getting Started video tutorial.
The best way to get help with layout problems is to upload the files to a website and post the URL in the forum. Someone can then look at the code, and identify the problem. Judging from your description, it sounds as though the Document window is narrow, which would result in the final menu tab dropping down to the next row. Try turning on Live view or previewing the page in a browser. Design view gives only an approximate idea of the final layout. Live view renders the page as it should look in a browser. -
New to Java and need help with this program..please!
I'd really appreciate any helpful comments about this program assignment that I have to turn in a week from Friday. I'm taking a class one night a week and completely new to Java. I'd ask my professor for help, but we can't call him during the week and he never answers e-mails. He didn't tell us how to call from other classes yet, and I just can't get the darn thing to do what I want it to do!
The assignment requirements are:
1. Change a card game application that draws two cards
and the higher card wins, to a Blackjack application
2. Include a new class called Hand
3. The Hand class should record the number of draws
4. The application should prompt for a number of draws
5. The game is played against the Dealer
6. The dealer always draws a card if the dealer's hand total is <= 17
7. Prompt the player after each hand if he wants to quit
8. Display the total games won by the dealer and total and the total games wond by the player after each hand
9. Display all of the dealer's and player's cards at the
end of each hand
10. Player has the option of drawing an additional card after the first two cards
11. The Ace can have a value of 11 or 1
(Even though it's not called for in the requirements, I would like to be able to let the Ace have a value of 1 or an 11)
The following is my code with some comments about a few things that are driving me nuts:
import java.util.*;
import javax.swing.*;
import java.text.*;
public class CardDeck
public CardDeck()
deck = new Card[52];
fill();
shuffle();
public void fill()
int i;
int j;
for (i = 1; i <= 13; i++)
for (j = 1; j <= 4; j++)
deck[4 * (i - 1) + j - 1] = new Card(i, j);
cards = 52;
public void shuffle()
int next;
for (next = 0; next < cards - 1; next++)
int rand = (int)(Math.random()*(next+1));
Card temp = deck[next];
deck[next] = deck[rand];
deck[rand] = temp;
public final Card draw()
if (cards == 0)
return null;
cards--;
return deck[cards];
public int changeValue()
int val = 0;
boolean ace = false;
int cds;
for (int i = 0; i < cards; i++)
if (cardValue > 10)
cardValue = 10;
if (cardValue ==1) {
ace = true;
val = val + cardValue;
if ( ace = true && val + 10 <= 21 )
val = val + 10;
return val;
public static void main(String[] args)
CardDeck d = new CardDeck();
int x = 3;
int i;
int wins = 1;
int playerTotal = 1;
do {
Card dealer = (d.draw());
/**I've tried everything I can think of to call the ChangeValue() method after I draw the card, but nothing is working for me.**/
System.out.println("Dealer draws: " + dealer);
do {
dealer = (d.draw());
System.out.println(" " + dealer);
}while (dealer.rank() <= 17);
Card mine = d.draw();
System.out.println("\t\t\t\t Player draws: "
+ mine);
mine = d.draw();
System.out.println("\t\t\t\t\t\t" + mine);
do{
String input = JOptionPane.showInputDialog
("Would you like a card? ");
if(input.equalsIgnoreCase("yes"))
mine = d.draw();
System.out.println("\t\t\t\t\t\t" + mine);
playerTotal++;
else if(input.equalsIgnoreCase("no"))
System.out.println("\t\t\t\t Player stands");
else
System.out.println("\t\tInvalid input.
Please try again.");
I don't know how to go about making and calling a method or class that will combine the total cards delt to the player and the total cards delt to the dealer. The rank() method only seems to give me the last cards drawn to compare with when I try to do the tests.**/
if ((dealer.rank() > mine.rank())
&& (dealer.rank() <= 21)
|| (mine.rank() > 21)
&& (dealer.rank() < 22)
|| ((dealer.rank() == 21)
&& (mine.rank() == 21))
|| ((mine.rank() > 21)
&& (dealer.rank() <= 21)))
System.out.println("Dealer wins");
wins++;
else
System.out.println("I win!");
break;
} while (playerTotal <= 1);
String stop = JOptionPane.showInputDialog
("Would you like to play again? ");
if (stop.equalsIgnoreCase("no"))
break;
if (rounds == 5)
System.out.println("Player wins " +
(CardDeck.rounds - wins) + "rounds");
} while (rounds <= 5);
private Card[] deck;
private int cards;
public static int rounds = 1;
public int cardValue;
/**When I try to compile this nested class, I get an error message saying I need a brace here and at the end of the program. I don't know if any of this code would work because I've tried adding braces and still can't compile it.**/
class Hand()
static int r = 1;
public Hand() { CardDeck.rounds = r; }
public int getRounds() { return r++; }
final class Card
public static final int ACE = 1;
public static final int JACK = 11;
public static final int QUEEN = 12;
public static final int KING = 13;
public static final int CLUBS = 1;
public static final int DIAMONDS = 2;
public static final int HEARTS = 3;
public static final int SPADES = 4;
public Card(int v, int s)
value = v;
suit = s;
public int getValue() { return value; }
public int getSuit() { return suit; }
public int rank()
if (value == 1)
return 4 * 13 + suit;
else
return 4 * (value - 1) + suit;
/**This works, but I'm confused. How is this method called? Does it call itself?**/
public String toString()
String v;
String s;
if (value == ACE)
v = "Ace";
else if (value == JACK)
v = "Jack";
else if (value == QUEEN)
v = "Queen";
else if (value == KING)
v = "King";
else
v = String.valueOf(value);
if (suit == DIAMONDS)
s = "Diamonds";
else if (suit == HEARTS)
s = "Hearts";
else if (suit == SPADES)
s = "Spades";
else
s = "Clubs";
return v + " of " + s;
private int value; //Value is an integer, so how can a
private int suit; //string be assigned to an integer?
}Thank you so much for offering to help me with this Jamie! When I tried to call change value using:
Card dealer = (d.changeValue());
I get an error message saying:
Incompatible types found: int
required: Card
I had my weekly class last night and the professor cleared up a few things for me, but I've not had time to make all of the necessary changes. I did find out how toString worked, so that's one question out of the way, and he gave us a lot of information for adding another class to generate random numbers.
Again, thank you so much. I really want to learn this but I'm feeling so stupid right now. Any help you can give me about the above error message would be appreciated.
Maybe you are looking for
-
Boot Camp / Windows Partion... Can it be installed on a separate hard drive
I am just beginning to explore the idea of installing Boot Camp & Windows on a new Intel Mac I will be buying. I've been reading a lot of references to the Windows partition... Can I dedicate a separate hard drive to Windows rather than partition my
-
Why does Sony multi-card reader show up now as a RealTek product?
I've had a Sony MRW62E/T1/181 card reader for several years. It worked fine until recently. When I plugged in the USB cord that came with it into my XP Pro SP3 computer, I got a message asking me to install a RealTek driver. To the best of my knowle
-
when I try to install icloud on my laptop running windows 7 home premieum I get message saying the windows installer package wont complete as a program run as part of setup did not finish as expected the install then rolls back I have tried rein
-
HT1933 Failure to download a TV episode
Using iTunes I bought a TV series and the first 8 episodes downloaded successfully using "check for available downloads". Now the latest two episodes will not download using the same process. I go to my "Purchase History" and click on "Report a Probl
-
What is the logical message type for Inbound Credit Memo (MM)
Hi Folks, What is the logical message type for Inbound Credit Memo (MM) Plz explain. Thanks, Matt