0

I'm new to Java. I'm learning by myself without guide. Can anyone help me with this little piece of code? What am I doing wrong??

package Lessons; import java.util.Scanner; public class lesson1 { public static void main (String []Args) { Scanner input = new Scanner (System.in); int age; System.out.println("How old are you?"); age = input.nextInt(); if (age >= 20); System.out.print("You Passed!"); else ( age <= 20) System.out.println("You Failed!"); } } 

The issue is in else. I'm working on Eclipse and I don't get any help solution from it on what to do.

5
  • 4
    if (age >= 20); - remove ; and also remove ( age <= 20) Commented Apr 18, 2017 at 10:23
  • 3
    Recommendation: always use { and } to delimit the statements that you want to run after an if and after the matching else. Otherwise, madness ensues. Commented Apr 18, 2017 at 10:25
  • 1
    Eclipse has a code-formatter. That will fix indentation and the bug becomes obvious. Use it. Commented Apr 18, 2017 at 10:26
  • 1
    @GhostCat how can you say "sure it works" for that which compileth not? Commented Apr 18, 2017 at 10:27
  • @DavidWallace Touche. But then: I hope you are really not encouraging to use ?: over if/else here? Commented Apr 18, 2017 at 10:30

2 Answers 2

3

First, you have ";" after if. Why?

Also you shouldn't write "else (...)", at least "else if(...)"

So, the correct code, if I understand right what you want is:

package Lessons; import java.util.Scanner; public class lesson1 { public static void main(String[] Args) { Scanner input = new Scanner(System.in); int age; System.out.println("How old are you?"); age = input.nextInt(); if (age >= 20) { System.out.print("You Passed!"); } else { System.out.println("You Failed!"); } } } 
Sign up to request clarification or add additional context in comments.

1 Comment

i dont know why i put it them haha, like i said i started few weeks ago and i dont really know even the basics :) by the way it worked, it was what i want it. thanks
2

It is recommended to add curly braces too see what if-else statements cover.

What you need however is to remove semicolon and remove boolean expression from else statement

 Scanner input = new Scanner(System.in); int age; System.out.println("How old are you?"); age = input.nextInt(); // Added {} and removed ; if (age >= 20) { System.out.print("You Passed!"); // Added curly brackets and removed boolean expression } else { System.out.println("You Failed!"); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.