1. Сравняване на низове

Всичко това е добре. Но можете да видите, че низовете s1и s2всъщност са еднакви, което означава, че съдържат един и същ текст. Когато сравнявате низове, How казвате на програмата да гледа не addressите на Stringобектите, а тяхното съдържание?

За да ни помогне с това, класът на Java Stringима equalsметода. Извикването изглежда така:

string1.equals(string2)
Сравняване на два низа

Този метод връща, trueако низовете са еднакви и falseако не са еднакви.

Пример:

Код Забележка
String s1 = "Hello";
String s2 = "HELLO";
String s3 = s1.toUpperCase();

System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s2.equals(s3));
// Hello
// HELLO
// HELLO

false // They are different
false // They are different
true // They are the same, even though the addresses are different

Още примери:

Код Обяснение
"Hello".equals("HELLO")
false
String s = "Hello";
"Hello".equals(s);
true
String s = "Hel";
"Hello".equals(s + "lo");
true
String s = "H";
(s + "ello").equals(s + "ello");
true

4
Задача
Java Syntax,  нивоурок
Заключено
Minimum of two numbers
All search and sort algorithms are based on comparisons. You'll be able to handle these very soon, if you so desire. In the meantime, we suggest starting with something small: write a program to find the minimum of two numbers. Find it and then display it. And if the numbers are the same, display either of them.
4
Задача
Java Syntax,  нивоурок
Заключено
Maximum of four numbers
Finding the maximum is an n-ary operation (an operation on n numbers) that returns the largest of several numbers. Never mind. We have no need for such definitions at the secret CodeGym center. We're here to learn how to write code. In this task, you need to use the keyboard to enter four numbers. Then determine the largest of them and display it on the screen.

2. Сравнение на низове без meaning за малки и главни букви

В последния пример видяхте, че сравнението дава . Наистина низовете не са равни. Но..."Hello".equals("HELLO")false

Ясно е, че низовете не са равни. Въпреки това съдържанието им има едни и същи букви и се различава само по регистъра на буквите. Има ли няHowъв начин да ги сравним и да пренебрегнем регистъра на буквите? Тоест, така че дава ?"Hello".equals("HELLO")true

И отговорът на този въпрос е да. В Java типът Stringима друг специален метод: equalsIgnoreCase. Извикването изглежда така:

string1.equalsIgnoreCase(string2)

Името на метода се превежда приблизително като сравняване, но пренебрегване на главни и малки букви . Буквите в името на метода включват две вертикални линии: първата е малка L, а втората е главна i. Не позволявайте това да ви обърква.

Пример:

Код Забележка
String s1 = "Hello";
String s2 = "HELLO";
String s3 = s1.toUpperCase();

System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.equalsIgnoreCase(s3));
System.out.println(s2.equalsIgnoreCase(s3));
// Hello
// HELLO
// HELLO

true
true
true

8
Задача
Java Syntax,  нивоурок
Заключено
Sorting three numbers
Planet Linear Chaos is populated by isomorphs. They are believed to have invented sorting algorithms. Everything in their heads is extremely well-ordered. They only issue planetary visas to people who know at least 7 sorting algorithms. Let's take our first step toward Linear Chaos: Read three numbers from the keyboard, put them in descending order, and then display them on the screen.

3. Пример за сравнение на низове

Нека дадем само един прост пример: да предположим, че трябва да въведете два реда от клавиатурата и да определите дали са еднакви. Ето How ще изглежда codeът:

Scanner console = new Scanner(System.in);
String a = console.nextLine();
String b = console.nextLine();
String result = a.equals(b) ? "Same" : "Different";
System.out.println(result);

4. Интересен нюанс на сравнение на низове

Има един важен нюанс, който трябва да знаете.

Ако компилаторът на Java намери множество идентични низове във вашия code (по-специално във вашия code), тогава той ще създаде само един обект за тях, за да спести памет.

String text = "This is a very important message";
String message = "This is a very important message";

И ето Howво ще съдържа паметта като резултат:

сравнение на низове

И ако сравните text == messageтук, тогава ще получите true. Така че не се изненадвайте от това.

Ако по няHowва причина наистина се нуждаете референциите да са различни, тогава можете да напишете това:

String text = "This is a very important message";
String message = new String ("This is a very important message");

Или това:

String text = "This is a very important message";
String message = new String (text);

И в двата случая променливите textи messageсочат към различни обекти, които съдържат един и същи текст.


4
Задача
Java Syntax,  нивоурок
Заключено
Jen or Jen?
Jen, Company X's admin, learned how to pilot a space ship and flew away to another planet. People in Company X are good and sincere. It's just that they're scatterbrained and they mix up names. So they decided that the new administrator would also be called Jen. Let's help Company X find their Jen: write a program that checks the identity of two entered names.