Operator! = does not work as I expect in Java [duplicated]

1

I am trying to solve it because in my do-while function when executing it within my program, if I type "Q" or "q" the execution continues instead of exiting the loop:

public void enroll() {
    // Get inside a loop, user hits Q to exit
    Scanner in = new Scanner(System.in);
    String course;      
    do {            
        System.out.print("Enter course to enroll (Q to quit): ");
        course = in.nextLine();
        courses = courses + "\n" + course;
        tuitionBalance = tuitionBalance + costOfCourse;         
    } while (course != "Q".toLowerCase());
    System.out.println("Enrolled in: " + courses);
    System.out.println("Tuition balance: " + tuitionBalance);
}

Thank you in advance for any help

    
asked by ChairoDev 23.03.2018 в 23:15
source

4 answers

3

String comparison is done using the equals ()

  

equals () Indicates if any other object is "equal to" this.

Review this question:

How to correctly compare Strings (and objects) in Java?

therefore change your comparison, and since you want to search when they are not different use ! and to normalize to lowercase use the method toLowerCase () :

...
} while (!course.toLowerCase().equals("q"));
...

This way, it will exit the loop when the letter is "Q" or "q".

You can also use the method trim () to eliminate possible spaces:

  ...
  } while (!course.toLowerCase().trim().equals("q"));
  ...
    
answered by 23.03.2018 / 23:18
source
0

To make String comparisons, equals() is used and operator != compares reference to objects. Your code would be as follows:

public void enroll() {
    // Get inside a loop, user hits Q to exit
    Scanner in = new Scanner(System.in);
    String course;      
    do {            
        System.out.print("Enter course to enroll (Q to quit): ");
        course = in.nextLine();
        courses = courses + "\n" + course;
        tuitionBalance = tuitionBalance + costOfCourse;         
    } while (!course.toLowerCase().equals("q"));
    System.out.println("Enrolled in: " + courses);
    System.out.println("Tuition balance: " + tuitionBalance);
}

Review this SO question

Another SO Spanish question

    
answered by 23.03.2018 в 23:22
0

The data types String do not compare to != , but with nombreVariable.equals("Q")

try so you can see.

    
answered by 23.03.2018 в 23:18
0

With equals , String objects or strings are compared, To be equal is nombreVariable.equals("Q"); To be different is !nombreVariable.equals("Q"); with ! at the beginning

    
answered by 23.03.2018 в 23:20