0

I have to break out of the loop if the user inputs a specific input. But I am unable to do that using the if loop to break out of the while loop. I also tried using the same condition in the while loop as well, but that doesn't work either.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {    
        String quit;
        Scanner c = new Scanner(System.in);

        while (true) {
            leapOrNot y = new leapOrNot();  
            System.out.println("press x to stop or any other letter to continue");
            quit = c.next();
            if (quit == "x" || quit == "X") {
                break;
            }
       }
    }
}

class leapOrNot {
    final String isLeap = " is a leap year.";
    final String notLeap = " is not a leap year.";
    int year;
    public leapOrNot() {
        Scanner a = new Scanner(System.in);
        System.out.println("Enter a year after 1581: ");
        year = a.nextInt();
        /* if (a.hasNextInt() == false) {
            System.out.println("Enter a 4 digit integer: ");
            year = a.nextInt();
        }
        couldn't make this condition work either
        */
        while (year < 1582) {
            System.out.println("The year must be after 1581. Enter a year after 1581: ");
            year = a.nextInt();
            continue;
        }

        if (year % 4 == 0) {
            if(year % 400 == 0 && year % 100 == 0) {
                System.out.println(year + isLeap);
            }
            if (year % 100 == 0) {
                System.out.println(year + notLeap);
            }
            else { 
                System.out.println(year + isLeap);
            }
        }
        else {
            System.out.println(year + notLeap);
        }
    }
}
  • Tip: `c.next().toLowerCase()` will help reduce your equality – OneCricketeer Feb 11 '17 at 03:38
  • Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Feb 11 '17 at 03:38

1 Answers1

0

You are supposed to use String.equals(). Replace with either of these two

  • if (quit.charAt(0) == 'x' || quit.charAt(0) == 'X')
  • if (quit.equals("x") || quit.equals("X"))

Any of the above will work fine.

or just use if(quit.equalsIgnoreCase("x"))

Pbd
  • 1,219
  • 1
  • 15
  • 32