java - Double answers in the coin flip code -


i new java. got assignment write program generates random number. program must assign "heads" or "tails" number, , ask user guess whether heads or tails. if user inputs right answer, program should respond "good guess!". if user inputs wrong answer, program should respond "oops!".

my program doesn't work correctly. no matter user guesses, outputs "good guess!". when selects "tails" , user guesses incorrectly, additionally outputs "oops!". when user guesses "heads" program never outputs "oops!" response @ all.

this wrote:

import java.util.scanner; public class headsortails {     public static void main(string[] args) {         int num1 = (int)(math.random() * 2);         system.out.println ("enter heads or tails");         scanner user_input = new scanner (system.in);         string flip = user_input.next();          if (flip.equals ("heads") && (num1 == 1)) {         }         system.out.println ("good guess!");         {             if (flip.equals ("tails") && (num1 == 1)) {                 system.out.println ("oops!");                    if (flip.equals ("heads") && (num1 == 0)) {                     system.out.println ("oops!");                     if (flip.equals ("heads") && (num1 == 0)) {                         system.out.println ("good guess!");                     }                 }             } 

when indented, code posted looks this:

import java.util.scanner;   public class headsortails {     public static void main(string[] args) {          int num1 = (int)(math.random() * 2);          system.out.println ("enter heads or tails");         scanner user_input = new scanner (system.in);          string flip = user_input.next();           if (flip.equals ("heads") && (num1 == 1)) {         }         system.out.println ("good guess!"); {         if (flip.equals ("tails") && (num1 == 1)) {             system.out.println ("oops!");                if (flip.equals ("heads") && (num1 == 0)) {                 system.out.println ("oops!");                 if (flip.equals ("heads") && (num1 == 0)) {                     system.out.println ("good guess!");                 }             }         }     } } 

it's clear see code isn't doing quite want do.

as @erwin bolwidt correctly pointed out, first "good guess" output incorrectly placed outside of if block.

the rest of if blocks nested when shouldn't - should if-then-else blocks.

please take @ article: the if-then , if-then-else statements


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -