문제

This code compares text entered by the user (userText) with a keyword (endProgram). When the user enters the word exit, the program will complete and close.

public static void main(String[] args) {

    String endProgram = "exit";
    String userInput;

    java.util.Scanner input = new java.util.Scanner(System.in);

    do {
        userInput = input.nextLine();
    } while ( !(userInput.equals(endProgram)) );

}

Is there a better way to write the code within the while parenthesis? That is, instead of using !(String.equals(String)) is there another function to compare inequality?

도움이 되었습니까?

해결책

Considering that ! is just one character, there's not much point in having a separate inequality test function that would just return the negation of the equality function.
So no.

다른 팁

You can use String.compareTo(String) which would return 0 when Strings are the same. It is more general than String.equals(String) as it performs lexical comparison and can be used for ordering (i.e. "a" < "b"). It has an compareToIgnoreCase() variant which would be better in your case as "EXIT" sounds just as valid as "exit".

The equals() method is actually performing comparison on an Object, not a String (though it will fail if the Object is not an instance of String). Its equalsIgnoreCase() variant though, is taking a String as a parameter.

If you don't like the "equal approach" (but the code you just wrote is right), you could use an integer as exit condition.

In that case, I suggest the use of hasNextInt().

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top