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;
}
Related
But if I put it to "valid = false;" it does not work in debug or running.
In fact even running the code, I can't type anything after the "Do you want to order anything else?", no matter if it's in debug or running mode.
Am I missing something? After asking "how many you want to order" and you put in a number after it should ask "do you want to order anything else" which is does but then I can't type and break out of the do while loop. Everything else is working up to that point.
do {
boolean itemValid = true;
while (itemValid) {
System.out.println("Please enter an item name: ");
String enterItem = scnr.nextLine();
if (keepTrack.containsKey(enterItem)) {
System.out.println(keepTrack.get(enterItem));
itemValid = false;
} else {
System.out.println("Sorry we don't exist.");
continue;
}
System.out.println("How many do you want to order?");
int enterQuan = scnr.nextInt();
yourOrder = enterQuan;
valid = false;
}
System.out.println("Do you want to order anything else?");
String yesNo = scnr.nextLine();
if (yesNo.equalsIgnoreCase("n")) {
valid = false;
} else
break;
} while (valid);
Two problems with your code. First, probably unnoticed yet:
do ...
if (keepTrack.containsKey(enterItem)) {
System.out.println(keepTrack.get(enterItem));
itemValid = false;
} else {
System.out.println("Sorry we don't exist.");
continue;
}
When your input is "invalid", you turn into the else branch. The else branch continues the loop. The loop depends on value. Thus: as soon as you start with value=true, and then have an invalid input, you end up with a never-ending loop. Because nothing between the loop start and the continue statement will ever change the conditions that would end the loop.
Your actual question: when you call int enterQuan = scnr.nextInt() that does not consume the "ENTER" that you typed on the console. See here for details.
And there is another problem:
if (yesNo.equalsIgnoreCase("n")) {
valid = false;
} else
break;
}
When the user enters n or N, you go valid=false which ends the outer do-while loop. Thus: when the user enters anything else, the elsepath is taken. What is to be found in the else path? A break. Which also ends the do-while loop.
In other words: your code does exactly what you told it to do: to end the do-while loop, one way or the other.
The real answer is: you need to be much more careful what you put in your code. Each and any character matters. And when you put something into your code for an experiment: remember that it is there, and has effects.
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.
public class Basic {
public static void main (String []args){
int first = 1;
if (first == 1);{
System.out.println("I did it");
}
else {
System.out.println("I didnt do it");
}
I dont know what to do, is there a mistake and i followed all the steps in the tutorials i'm watching. It just says delete the token
Remove the semi-colon after (first == 1)
Remove the semicolon after if (first == 1);
The semicolon after makes the if statement finished and the block after {} is not a part of if.So the else part is complaing about the non-existence of if because else cannot exist without if
You should delete the obviously misplaced ; and finish all your opened brackets. Try this:
public class Basic
{
public static void main (String []args)
{
int first = 1;
if (first == 1)
{
System.out.println("I did it");
}
else
{
System.out.println("I didnt do it");
}
}
}
If you have problems with brackets, you can configure Eclipse to automatically put closed bracket under each other like in the example.
The semicolon you have placed there ended your if statement, so it had no effect on the code between the brackets. You can imagine (Java purists will pardon the simple explanation), that after if, there is only one command or command block allowed. The brackets will group more commands to one block.
Try this example, it will explain you how it works.
int i=1;
if (i==1)
System.out.println("I should be here when i==1");
else
System.out.println("Will this output be printed out? No, this is else section!");
if (i==2)
{
System.out.println("I should be here when i==2");
System.out.println("Will this output be printed out? No! Condition was not met, because i==1 and we are in the block");
}
if (i==2)
System.out.println("I should be here when i==2");
System.out.println("Will this output be printed out? Yes, because the commands are not in the block!");
if (i==2); //WATCH OUT, there is semicolon that terminated if statement
System.out.println("Will this output be printed out? Yes, because that semicolon has terminated the if statement!");
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);
}
This just is't making sense to me at all.
This is my code:
boolean that = false;
if (that == true);
{
System.out.println("That is " + that);
}
And yet it will print the line even though my output is
That is false
I'm doing this in java and I'm using Eclipse galileo, so each time I compile/run my program it saves it so the compiler should be getting updated version of my program.
What's going on?
A common mistake. Remove the ; at the end of the if statement.
BTW I always write the following if I use brackets and I use the code formatter of the IDE.
if (that == true) {
System.out.println("That is " + that);
}
This means if you have a mis-placed ; or { it can be more obvious.
Remove the ;
boolean that = false;
if (that == true)
{
System.out.println("That is " + that);
}
otherwise the print is always executed.
It's because of the semicolon you have here:
if (that == true);
Remove that semicolon ! It causes the code to do nothing after checking the conditional (that == true) - technically it's an "empty statement" - i.e. we can have a loop like so:
for (int i = 0; ; i++){
System.out.println("Thanks" );
}
And it would go forever!
Try it like this:
boolean that = false;
if (that)
{
System.out.println("That is " + that);
}
Notice the extra semi-colon after the if in your code? That's why.
The logical test is closed by the semi-colon, then the next block is always executed.
If you remove the semi-colon it'll match your intuition.
if (that == true);
// ^ The extra colon you dont need