How do I use an if statement to compare two inputs with grater than or less than

I need to compare the two inputs the user gives called age and answer2 in Java on repl.it I tried using greater than and less than signs, it still returns an error.

import java.util.*;
class Main {
  public static void main(String[] args) {
        Scanner vismay = new Scanner(System.in);
        System.out.println("What is your name?");
        String name = vismay.next();
        System.out.println("What is your age?");
        int age = vismay.nextInt();
        System.out.println("Hi "+name);
        System.out.println("You are "+age+" years old correct? Press t for true, f for false.");
        String answer = vismay.next();
        if(answer.equals("t")) {
            System.out.println("What is your favorite number?");
            int number = vismay.nextInt();
            String answer2 = vismay.nextInt();
            if(answer2.equals(age)){
                System.out.println("You are going to be very famous");
            }
            else if(answer2.lessthan(age)){
                System.out.println("You are going to be very rich");
            }
            else if(answer2.greaterthan(age)){
                System.out.println("You are very unlucky");
            }
        }
        else {
            System.out.println("What is your age?");
            int age2 = vismay.nextInt();
            System.out.println("You are "+age2+" years old correct? Press t for true, f for false.");
        }

  }
}

It returns:

Main.java:22: error: not a statement
          else (answer2.greaterthan(age)){
               ^

Main.java:22: error: ';' expected
          else (answer2.greaterthan(age)){
                                         ^

2 errors
compiler exit status 1

1 answer

  • answered 2019-07-10 22:35 Jason

    Firstly, you're asking for the user to enter their favourite number, but expecting two inputs:

    System.out.println("What is your favorite number?");
    int number = vismay.nextInt();
    String answer2 = vismay.nextInt();
    

    Secondly, you should be comparing an int to an int, not a string to an int. Change your code to the following:

    System.out.println("What is your favorite number?");
    int favoriteNumber = vismay.nextInt();
    if (favoriteNumber == age) {
        System.out.println("You are going to be very famous");
    }
    else if (favoriteNumber < age) {
        System.out.println("You are going to be very rich");
    }
    else if (favoriteNumber > age) {
        System.out.println("You are very unlucky");
    }