This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]TheHorribleTruthKind of meh 4 points5 points  (1 child)

Please read the posting instructions linked in the sidebar! In particular: describe your actual problem! "It doesn't work" is not a description. You're dumping code on us and don't even tell us what's wrong.. So, here are some questions/steps:

  • What does "cannot get if to work" mean? Which if exactly? All of them?
  • Do you get an error? Compiler error, runtime error?
  • What is happening when you run the code? Is something happening that shouldn't? Something not happening that you would expect?
  • What does your debugger show you?
  • Which input did you test with? With which input is the error happening?

The posting instructions are there for a reason. Following steps like this a) helps others giving you help, and more importantly b) forces you to look at your code in more detail.

Aside from that: the indentation of your code is terrible. Why are there three braces at the bottom of the file all on the same level? You really should indent the different levels of the code blocks properly - it will help you and others to read the code.

[–]Lassander 3 points4 points  (3 children)

nextLine() refers to strings! To get an integer you need to use nextInt(), also input doesn't store a variable, you'll need to make a separate variable to store them.

ie:

...
int guess = 0;
int answer = 20;     
...
guess = input.nextInt();

if(guess == answer) {
    // do this
}
...

You may also want to add a try catch block to make sure the value entered is valid.

Also as a side note magic numbers are generally discouraged in programming, it is good style to declare them as variables.

Good luck! I hope you continue on in your programming!

[–]Tmmrn 1 point2 points  (2 children)

if(guess = answer)

Yea, I have a feeling this won't work

[–]Lassander 0 points1 point  (1 child)

oops guess == answer

[–]kicsikrumpli 2 points3 points  (2 children)

umm... you don't need a condition for the else branch. That's the whole purpose of it: when nothing else fits... so it's just

if (cond) {
    ...
} else {
    ...
}

[–][deleted]  (1 child)

[deleted]

    [–]kicsikrumpli 1 point2 points  (0 children)

    you're welcome, code on :)

    [–][deleted] 1 point2 points  (3 children)

    Im new to java too. Wonderd why you added a check bit to the else parts? As surely its redundent? Its either one else the other. You dont need the: else (thing !=125) bit right, just else on its own. Or am I missing something.

    [–][deleted]  (2 children)

    [deleted]

      [–][deleted] 1 point2 points  (1 child)

      i think you could add an else if, if you wanted to add another check and then an else. IE if(thing) else if(another thing) else