La seconda guerra mondiale per licei e scuole medie
Stringhe java
1. Caratteri e Stringhe Unità didattica 4 Enrico Giunchiglia Gabriele Palma Fondamenti di Informatica
2.
3. Tabella ASCII (standard) Il carattere 'O' ha codice 79 ( riga 70 + col onna 9 = 79 ). O 9 70
4. Gestione di caratteri D ichiarazione ed inizializzazione char ch1; char ch2 = ' X ' ; Conversione tra int e char . uscitaDati.print( “ Codice ASCII di X: " ); uscitaDati.printLine((int) ' X ' ); uscitaDati.print(" Codice ASCII 88: "); uscitaDati.printLine((char) 88 ); true perchè il codice ASCII di 'A' è 65 e il codice di 'c' è 99 . ' A ' < ' c '
5.
6.
7.
8.
9.
10. E sempio : cont eggio di v o cali Queste istruzioni contano il numero di vocali nella stringa in ingresso (nome). String nome = richiestaDati.getString(" Nome ?"); int numeroVocali = 0; for (int i = 0; i < nome.length(); i++) { char letter = nome.charAt(i); if (letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U' ) { numeroVocali++; } } uscitaDati.print( " il tuo nome ha " + numeroVocali + " vocali ");
11. E sempio : co nteggio di parole (1) String frase = richiestaDati.getString(“ Dammi una frase :"); int nc = frase.length(); int indice = 0, numeroParole = 0; while (indice < nc) { // ignor a gli spazi bianchi while (frase.charAt(indice) == ' ') { indice++; } // trova la fine della parola while (frase.charAt(indice) != ' ') { indice++; } // un’altra parola trovata, incremento del contatore numeroParole++; } Problem a : Il ciclo più interno potrebbe assegnare ad indice un valore che eccede il massimo consentito (nc)
12. E sempio : cont eggio di parole (2) String frase = richiestaDati.getString(“ Dammi una frase :"); int nc = frase.length(); int indice = 0, numeroParole = 0; while (indice < nc) { // ignor a gli spazi bianchi while ((indice < nc) && (frase.charAt(indice) == ' ')) { indice++; } // trova la fine della parola while ((indice < nc) && (frase.charAt(indice) != ' ')) { indice++; } // un’altra parola trovata, incremento del contatore numeroParole++; } Problem a : numeroParole è maggiore di uno rispetto al conteggio corretto se la frase finisce con uno o più spazi.
13.
14. E sempio : confronto tra oggetti String int javaNum = 0; boolean ripeti = true; String parola; while ( ripeti ) { parola = inDati.getString(“ Prossima parola :"); if ( parola.equals("STOP") ) { ripeti = false; } else if ( parola.equalsIgnoreCase(“Java") ) { javaNum++; } } Continu a a leggere le parole e conta quante volte la parola Java appare nel testo in ingresso.
15. Uguaglianza (==) vs. equals (1) word1 == word2 word1.equals( word2 ) word1 e word2 p untano allo stesso oggetto. word1 word2 String Java true true
16. Uguaglianza (==) vs. equals (2) word1 word2 word1 == word2 word1.equals( word2 ) word1 e word2 p untano ad oggetti diversi con uguale contenuto. String Java true false String Java
17. Uguaglianza (==) vs. equals (3) word1 word2 word1 == word2 word1.equals( word2 ) word1 e word 2 p untano ad oggetti diversi con diversi contenuti. String Java false false String Bali
18. Altri metodi della classe St ring Me todo Significato substring x.substring(n,m) restituisce una stringa corrispondente alla porzione di x dalla posizione n alla posizione m String s = “Viva Java!”; String t = substring(1,3); // contiene “iva” trim x.trim() restituisce una stringa con lo stesso contenuto di x privato di eventuali spazi all’inizio e alla fine startsWith x.startsWith(y) restituisce true se x comincia con y String s = “Viva Java!”, t = “Viva”; boolean r = s.startsWith(t); endsWith x.endsWith(y) restituisce true se x termina con y String s = “Viva Java!”, t = “Java!”; boolean r = s.endsWith(t); indexOf x.indexOf(c) restituisce la posizione di c in x e x.indexOf(c,n) restituisce la posizione di c in x cominciando la ricerca dalla posizione n; entrambe restituiscono –1 se c non è presente in x (c di tipo char)
19.
20. Metodi di StringBuffer Me todo Significato charAt x.charAt(n) restituisce il carattere in posizione n (analogo alla classe String) length x.length() restituisce il numeo di caratteri in x (analogo alla classe String) setCharAt x.setCharAt(n, c) imposta il carattere in posizione n al valore c (c è di tipo char) deleteCharAt x.deleteCharAt(n) cancella il carattere in posizione n append x.append(y) concatena a x il contenuto di y reverse x.reverse() rovescia il contenuto di x insert x.insert(n,y) inserisce y all’interno di x a partire dalla posizione n delete x.delete(n,m) cancella dalla posizione n alla posizione m toString y = x.toString() restituisce il contenuto di x sotto forma di String (y è un oggetto String)
21. Utilizzo di StringBuffer (1) Rimpiazza tutte le vocali dell’oggetto frase con ' X ' String frase = richiestaDati.getString(“ Frase :"); StringBuffer temp = new StringBuffer(frase); for (int i = 0; i < temp.length(); i++) { char c = temp.charAt(i); if ( c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u' || c == 'U' ) { temp.setCharAt(i, 'X'); } } uscitaDati.print(temp);
22. Utilizzo di StringBuffer (2) Costruisce una frase con le sole parole di lunghezza pari String parola; StringBuffer temp = new StringBuffer(""); boolean ripeti = true; while ( ripeti ) { parola = inDati.getString(“ Prossima parola :"); if ( parola.equals("STOP") ) { ripeti = false; } else if ( parola.length() % 2 == 0 ) { temp.append(parola + " "); } } Aggiunge la parola e uno spazio a tempStringBuffer .
23.
24.
25.
26.
27. Gestire la selezione con ResponseBox int selection = yesNoBox.prompt(“ Premi un b o tton e "); switch (selection) { case ResponseBox.YES: messageBox.show(“ Hai premuto Yes"); break; case ResponseBox.NO: messageBox.show(“ Hai premuto No “); break; }
28. Esempio di utilizzo di ResponseBox choice = yesNoBox.prompt (“ Vuoi iniziare ad eseguire i calcoli ?"); while (choice == ResponseBox.YES) { // qui vengono eseguiti i calcoli choice = yesNoBox.prompt (“ Altri calcoli? "); }
29.
30.
Notas del editor
We have also seen the string concatenation operation. For example, the following code reads in a person’s name and greets the user: //assume inputBox and messageBox are declared //and initialized correctly String name; name = inputBox.getString(&quot;What is your name?&quot;); messageBox.show(&quot;Hello, &quot; + name + &quot;. Nice to meet you.&quot;);
When we write String name; we must say “name is a variable of type String whose value is a reference to an instance of String” to be precise. However, when the value of a variable X is a reference to an instance of class Y, we usually say “X is an instance of Y” or “X is a Y object.” For example, we say canvas is a DrawingBoard object
Remember that a String is an object. If we simply declare, for example, String str3; and forget to create a String object, then str3 is a null object. You will get a NullPointerException if you try to a method of non-existent object, such as str3 in this example.
Using the toUpperCase method, that converts all alphabetic characters to uppercase, we can rewrite the code as char letter; String name = inputBox.getString(&quot;What is your name?&quot;); int numberOfCharacters = name.length(); int vowelCount = 0; String nameUpper = name.toUpperCase(); for (int i = 0; i < numberOfCharacters; i++) { letter = nameUpper.charAt(i); if ( letter == 'A' || letter == 'E' || letter == 'I' || letter == 'O' || letter == 'U' ) { vowelCount++; } } messageBox.show(name + &quot;, your name has &quot; + vowelCount + &quot; vowels&quot;);
General idea expressed in pseudocode is as follows: read in a sentence; while (there are more characters in the sentence) { look for the beginning of the next word; now look for the end of this word; increment the word counter; }
See Exercise 8.17 on page 408. One approach to solve this “off-by-one” error is to use two counters to keep track of the begin index (the position of the first character) and the ending index (the position of the last character) of the words in a sentence. The second approach is to add an if statement after the outer while to determine whether the last index of the sentence is a blank or not. The third approach is to use the trim method of the String class. The trim method removes the leading and trailing blank spaces (actually all whitespaces and control characters) from a string. Question: Which approach is the best solution? Discuss.
Notice that we wrote word.equals( “STOP”) not word == “STOP” the two boolean expressions have quite different effects. We will describe their difference later.
Notice how the input routine is done. We are reading in a String object and converting it to a StringBuffer object, because we cannot simply assign a String object to a StringBuffer variable. For example, the following code is invalid: StringBuffer strBuffer = inputBox.getString( ); We are required to create a StringBuffer object from a String object as in String str = &quot;Hello&quot;; StringBuffer strBuf = new StringBuffer( str ); You cannot input StringBuffer objects. You have to input String objects and convert them to StringBuffer objects.
Notice that we can write the code using only String objects: boolean repeat = true; String word, newSentence; newSentence = &quot;&quot;; //empty string while ( repeat ) { word = inputBox.getString(&quot;Next word:&quot;); if ( word.equals(&quot;STOP&quot;) ) repeat = false; else if ( word.length() % 2 == 0 ) newSentence = newSentence + word; //string concatenation } Whether we use String or StringBuffer depends on the problem we try to solve.