this is my first post so please bear with me. I am trying to produce a program that lets a user play black jack against the computer. the following code let the player take their turn:
//method for the players turn
public static void playersTurn()
{
String playersCard = dealSingleCard();
playerHand.add(playersCard);
String playersActualHand = cardRepresentation(playersCard);
System.out.println(playersActualHand);
//System.out.println(playerHand);
System.out.println(calculateHandValue(playerHand));
Scanner in = new Scanner(System.in);
System.out.println("Stick or Twist?");
String stickOrTwist = in.next();
String twist = "t";
String stick = "s";
//int total = 0;
//int playerTotal = calculateHandValue(playerHand) + total;
if (calculateHandValue(playerHand) < 21)
{
if (stickOrTwist .equalsIgnoreCase (twist));
{
dealSingleCard();
}
if (stickOrTwist .equalsIgnoreCase (stick))
{
calculateWinner();
}
}
}
I cant seem to get the "twist" if statement to work, the program just stops. The "stick if statement work fine. what am i doing wrong?
You have a little syntax error, since you put a semicolon after the if condition, here:
if (stickOrTwist .equalsIgnoreCase (twist));
Remove it and it should work fine.
Change the below code
if (calculateHandValue(playerHand) < 21)
{
if (stickOrTwist .equalsIgnoreCase (twist));
{
dealSingleCard();
}
if (stickOrTwist .equalsIgnoreCase (stick))
{
calculateWinner();
}
}
with
if (calculateHandValue(playerHand) < 21)
{
if (stickOrTwist .equalsIgnoreCase (twist))
{
dealSingleCard();
}
if (stickOrTwist .equalsIgnoreCase (stick))
{
calculateWinner();
}
}
The line terminator ';' should not be used with the if condition.
the only problem with your code is that you have placed ';' after the if statemt.So the compiler is not executing the body of if.Try removing the semicolon as:
if (stickOrTwist .equalsIgnoreCase (twist))
{
dealSingleCard();
}
I just assume from the way you used dealSingleCard() at the beginning of the methode, you want todo the following:
if(stickOrTwist.equalsIgnoreCase(twist)){
playerHand.add(dealSingleCard());
}
The rules of blackjack (or pontoon as it was called when I was growing up) are that a player can repeatedly twist until (s)he either decides to stick or her hand value exceeds 21. This repeated behaviour is absent from your code.
Instead of
if (calculateHandValue(playerHand) < 21)
you should have a loop
while (calculateHandValue(playerHand) < 21)
and inside the while loop, you ask if the player will stick or twist. Break out of the loop if the player sticks and then process the bust condition. You should only call the calculateWinner() method once all the players have played.
Related
I wrote a method in order to get the choice of the user for the size of a grid. However, my code doesn't seem to work after executing the method, as it continues to run without end after I type in the response to console (if it matters, I am on repl.it). What is the issue with the code that prevents it from ending?
public static String createSize() {
int count = 0;
String answer = "";
Scanner sc = new Scanner(System.in);
System.out.println("How big do you want the grid? (Sizes: 4x4, 5x5, 6x6)");
String size = sc.nextLine();
//Checks if user-inputted answer matches possible answers
while (count < 1) {
if (size.equals("4x4") || size.equals("5x5") || size.equals("6x6")) {
count++;
answer = sc.nextLine();
}
else {
System.out.println("That was not a viable size. Please type a viable size.");
size = sc.nextLine();
}
}
sc.close();
return answer;
}
In the first If check in the while loop
Change
answer = sc.nextLine();
to
answer = size;
since u do not want the user to input size twice.
Your code should work fine now.
Let me know if anything isn't clear so I can modify and elaborate further
what's the main problem? I tried to run this code on all possible test cases and I didn't get any problem.
In the if statement you have answer = sc.nextLine(); which will again ask you for the input that's why the program was not executing further. If you pass input second time only then it will execute. Further in if statement answer wasn't assigned any value so even after entering two values it will not return anything.
Correction :-
if (size.equals("4x4") || size.equals("5x5") || size.equals("6x6")) {
count++;
answer = size;
}
public void talk() {
String[] prompts = {"Describe to me in a sentence why this is a cool program.",
"Describe to me in a sentence how your day was.",
"Describe to me in a sentence what programming means to you.",
"Describe to me in a sentence why food is neccessary for humans."};
iramInLoop = true;
while(iramInLoop)
{
int i = new Random().nextInt(prompts.length);
System.out.println(prompts[i]);
String input = Raybot.getInput();
if(!checkPunc(input) && !checkCaps(input)){
System.out.println("Check your capitalization and your punctuation!");
}
else{
System.out.println("Great grammar keep it up! Do you want to try again?");
if(input.equals("yes")) continue;
else
{
iramInLoop = false;
Raybot.talkForever();//this exits the loop
}
}
}
}
I am having extreme trouble trying to restart my loop. So at the end of my code when the loop is done running I put a string which asks if the user wants to try again and if the user says yes I want it to go back to the beginning of the loop and do what the loop does again. However, every time I run it it goes to the end of the loop and doesn't even ask for an input.
I think you should be breaking out of the loop if the person guessed right, but then decided not to continue. In this case, your logic should be something like this:
while (true) {
int i = new Random().nextInt(prompts.length);
System.out.println(prompts[i]);
String input = Raybot.getInput();
if (!checkPunc(input) && !checkCaps(input)) {
System.out.println("Check your capitalization and your punctuation!");
}
else {
System.out.println("Great grammar keep it up! Do you want to try again?");
input = Raybot.getInput();
if (input.equals("no")) {
break;
}
}
}
// whatever this does, you intended for it happen after the loop terminates, so do it here
Raybot.talkForever();
You are missing to actually accept any input
maybe
System.out.println("Great grammar keep it up! Do you want to try again?");
input = Raybot.getInput();
change if(input.equals("yes")) continue;
to if(Raybot.getInput().equals("yes")) continue;
import java.util.Scanner;
public class SherlockHolmes {
String answer = "Watson";
String response = " ";
int tries = 0;
int tries = 3;
Scanner input = new Scanner(System.in); {
System.out.print("Enter the name of Sherlock's partner, and dear friend.");
response = input.nextLine();
tries++;
if (response.equals("Watson"))
else
while (tries <= 3)
System.out.print("Ooooh, sorry kid! Try again!"); {
System.out.println("Yes, that's right, Barrel Rider.");
break;
} else if (tries == 3) {
System.out.println("Ooooo, sorry kid. But, it looks like you're S.O.L!");
break;
}
}
}
My biggest question is why I'm getting two errors with this method, the error
being: SherlockHolmes.java:16: error: 'else' without 'if'
else
^
SherlockHolmes.java:24: error: 'else' without 'if'
else if(tries == 3)
^
2 errors
I put if code in every line, yet its telling me : "Else without if" for both entries of "else". I am kind of frustrated, and I don't slagging get how Java thinks I have no if when it is clearly there!
What am I doing wrong that Java thinks I have no if code fashioned in?
If you want an if statement with an empty body, you NEED curly braces in Java. Honestly, you should just have way more braces in your code. I strongly suggest reading up on Java coding conventions http://www.oracle.com/technetwork/java/codeconventions-150003.pdf
Example:
if (response.equals("Watson"))
else while (tries <= 3)
For that empty if to compile, you need:
if (response.equals("Watson")) {
}
else while (tries <= 3) {
// loop body
}
You have many syntax errors.
First, you cannot attach an else-if to a while block. Second, if you're trying to make it so that if the response does not equal "Watson", then use the "not equal to" operator, which is simply "!" (an exclamation mark).
Control flow is made up of
if (condition) {} Must be used once, and must be first
else if (condition) {} as many times as you want, optional, must be in between else and if if included
else {} optional, must be last and used once if included
Curly braces and order are mandatory. In Java, it is best practice, and usually required to put curly braces around all blocks: if, while, for. Another thing you need to know is that while loops are not the same as conditionals. They can't be attached to else or else if statements. So your while loop needs to change to
while (tries <= 3) {
...
}
Do this similarly with the conditional statements.
System.out.print("Enter the name of Sherlock's partner, and dear friend.");
response = input.nextLine();
tries++;
while (tries <= 3) {
if (response.equals("Watson")) {
System.out.println("Yes, that's right, Barrel Rider.");
}
else {
System.out.print("Ooooh, sorry kid! Try again!");
break;
}
if (tries == 3) { // If the while loop finishes
System.out.println("Ooooo, sorry kid. But, it looks like you're S.O.L!");
break;
}
I've been asked to get user input and ignore values that don't fall within the range of -30 and 40. To skip over invalid numbers I use a 'continue' statement. I've googled sources saying continue / break are bad practice. The IDE is also throwing an "unnecessary continue" warning. Is the code below good practice in solving this problem, should I just override the warning or address it?
My code is as shown below:
public class Temperatures
{
#SuppressWarnings("UnnecessaryContinue")
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// Write your code here.
while(true)
{
//ask user for input
double userInput = Double.parseDouble(reader.nextLine());
//makes sure temperature is within range, if it isn't ignores value and moves on
if (userInput < -30.0 || userInput > 40.0)
{
continue;
}
//adds value to graph
else
{
Graph.addNumber(userInput);
}
}
}
Possibly the IDE is showing the warning because if you removed the continue your code would work exactly the same. Think about it.
The IDE is also throwing an "unnecessary continue" warning.
It is an unnecessary continue. Why?
If your if statement turns true, else would not be executed. If the if condition is false, else would be executed. Hence, there is no need of a continue here.
continue should have been used if:
while(true)
{
double userInput = Double.parseDouble(reader.nextLine());
if (userInput < -30.0 || userInput > 40.0)
{
continue;
}
Graph.addNumber(userInput);
}
There is no else statement, hence now you have to use a continue to skip the further execution of the current iteration.
You don't need to use continue in your case. Use this instead:
if( userInput >= -30 && userInput <= 40){
Graph.addNumber(userInput);
}
I'm writing a Java program in which I'm checking a list against a string, and then doing stuff to that. In fortran I'd write something along the lines of
where(list(:)==stringToCheck){
...
statements
...
}
Instead I have a headache of a block of for-loops, if staments and breaks all over the place. No perhaps I could neaten the code a little but it still feels far more inefficient than fortran.
Edit, this is the code I've resorted to:
for(int idx=0;idx<player.get_charactersOwned().size();idx++)
{
if(player.get_charactersOwned().get(idx).get_characterName().equals(charName))
{
/* Add character to the game
* Add game to the character*/
System.out.println("Character "+charName+" Found ");
gameToMake.addCharacters(player.get_charactersOwned().get(idx));
player.get_charactersOwned().get(idx).addGame(gameToMake);
break;
}else
{
System.err.println("Character "+ charName +" not found");
System.out.println("Shall I add that Character? y/n ");
choice = scanner.nextLine();
if(choice.equalsIgnoreCase("y"))
{
charName = scanner.nextLine();
Character character = new Character(charName);
characterTempList.add(character);
player.addCharacter(characterTempList);
gameToMake.addCharacters(player.get_charactersOwned().get(idx));
player.get_charactersOwned().get(idx).addGame(gameToMake);
break;
}else{break;}
}
}
As tempting as it is to fix this code, I'd much rather use a work around.
Is there a Java equivilant of this without the use of external libraries?
No, there isn't an equivalent in Java. Instead if you need to check if a list of characters (each with a name) contains a character name then simply do this:
// search the name
boolean found = false;
for (Character c : player.get_charactersOwned()) {
if (c.get_characterName().equals(charName)) {
found = true;
break;
}
}
// perform the check
if (found) {
// do something
} else {
// do something else
}
And by the way, Character is a bad name for your class, it clashes with Java's own Character class. Rename it if possible, to avoid confusion. Alternatively, the loop could have been written like this:
boolean found = false;
for (int i = 0, n = player.get_charactersOwned().size(); i < n && !found; i++) {
Character c = player.get_charactersOwned().get(i);
if (c.get_characterName().equals(charName)) {
found = true;
}
}