1. Confronto tra stringhe

Va tutto bene. Ma puoi vedere che le stringhe s1e s2sono in realtà le stesse, nel senso che contengono lo stesso testo. Quando confronti le stringhe, come dici al programma di guardare non gli indirizzi degli Stringoggetti, ma il loro contenuto?

Per aiutarci in questo, Stringla classe di Java ha il equalsmetodo. Chiamandolo sembra così:

string1.equals(string2)
Confronto tra due stringhe

Questo metodo restituisce truese le stringhe sono le stesse e falsese non sono le stesse.

Esempio:

Codice Nota
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

Altri esempi:

Codice Spiegazione
"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
Compito
Java Syntax,  livello 4lezione 6
Bloccato
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
Compito
Java Syntax,  livello 4lezione 6
Bloccato
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. Confronto di stringhe senza distinzione tra maiuscole e minuscole

Nell'ultimo esempio, hai visto che il confronto produce . In effetti, le stringhe non sono uguali. Ma..."Hello".equals("HELLO")false

Chiaramente, le stringhe non sono uguali. Detto questo, il loro contenuto ha le stesse lettere e differisce solo per il caso delle lettere. C'è un modo per confrontarli e ignorare il caso delle lettere? Cioè, in modo che rendi ?"Hello".equals("HELLO")true

E la risposta a questa domanda è sì. In Java, il Stringtipo ha un altro metodo speciale: equalsIgnoreCase. Chiamandolo sembra così:

string1.equalsIgnoreCase(string2)

Il nome del metodo si traduce approssimativamente come compare ma ignore case . Le lettere nel nome del metodo includono due linee verticali: la prima è minuscola Le la seconda è maiuscola i. Non lasciarti confondere.

Esempio:

Codice Nota
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
Compito
Java Syntax,  livello 4lezione 6
Bloccato
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. Esempio di confronto tra stringhe

Facciamo solo un semplice esempio: supponiamo di dover inserire due righe dalla tastiera e determinare se sono uguali. Ecco come apparirà il codice:

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. Un'interessante sfumatura del confronto tra stringhe

C'è una sfumatura importante di cui devi essere consapevole.

Se il compilatore Java trova più stringhe identiche nel tuo codice (in particolare nel tuo codice), creerà solo un singolo oggetto per loro per risparmiare memoria.

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

Ed ecco cosa conterrà la memoria come risultato:

confronto di stringhe

E se confronti text == messagequi, ottieni true. Quindi non essere sorpreso da questo.

Se per qualche motivo hai davvero bisogno che i riferimenti siano diversi, puoi scrivere questo:

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

O questo:

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

In entrambi i casi, le variabili texte messagepuntano a oggetti diversi che contengono lo stesso testo.


4
Compito
Java Syntax,  livello 4lezione 6
Bloccato
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.