So after the get number of characters method I'll add another method. From the
fact sheet we can see that the index of method will help us. We want to return
bookText.indexOf Mad hatter. Now we need to add that line to our test program,
BookTester which prints out the actual value of
Alice.firstOccurrenceOfMadHatter, looks like I capitalized it wrong. Alright,
now let's see what this actually gives us. Huh, the actual value is negative
one. That doesn't sound like a location. There shouldn't be a minus one
character in the book. Let's look at the documentation. In my browser, I'll
search for java 7 string and find the official documentation. And then I'm
going to look for the index of method. Methods, index of, we're giving it a
string. Alright, returns the index within this string of the first occurrence
of the specified substring. That's what we were expecting. The returned index
is the smallest value, k, for which this dot starts with stir, k. Not sure what
that means yet, we can think about that later. If no such value of k exists.
Then minus 1 is returned. Okay, so minus 1 means that there are no occurrences
of Mad Hatter as we wrote it in the book. This might be surprising. The Mad
Hatter is a famous charater. But it turns out, in the book, he's always just
called the Hatter, not the Mad Hatter.
Después de el método para obtener el número de caracteres, voy a añadir otro método. De la
ficha de información, podemos ver que el método indexOf (indiceDe) nos ayudará. Queremos devolver
bookText.indexOf ("Sombrero Loco"); Ahora tenemos que añadir esta línea a nuestro programa de pruebas,
BookTester, que imprime el valor real de
Alice.firstOccurrenceOfMadHatter (Alicia.primerAparicionDeSombrereroLoco), parece que lo puse mal en mayúsculas. Muy bien.
Ahora vamos a ver lo que esto nos da en realidad. ¿Eh?, el valor real es 1
negativo. Eso no suena como una ubicación. No debería haber un caracter
menos 1 en el libro. Echemos un vistazo a la documentación. En mi navegador, voy a
buscar «Cadena java 7» y encontraré la documentación oficial. Y luego voy
a buscar el método indexOf. Métodos... indexOf... le estamos dando una
cadena. Muy bien, devuelve el índice dentro de esta cadena de la primera incidencia
de la subcadena especificada. Eso es lo que estábamos esperando. El índice de regreso
es el más pequeño valor, k, para el que este punto inicia con str, k. No estoy segura de lo que
eso significa, sin embargo, podemos pensar en eso más adelante. Si no existe tal valor de k.
entonces menos 1 es devuelto. Ok, menos 1 significa que no hay incidencias
de Sombrero Loco, como lo escribimos, en el libro. Esto podría ser sorprendente. El Sombrero Loco
es un personaje famoso. Pero resulta que, en el libro, siempre es
llamado como Sombrerero, no Sombrerero Loco.
Donc, après la méthode getNumCharacters,
je vais ajouter une autre méthode.
De la fiche d'information,
nous pouvons voir que
l'index de la méthode nous aidera.
Nous voulons renvoyer
bookText.indexOf (Mad Hatter).
Nous devons ajouter cette ligne
à notre programme test,
BookTester qui imprime la valeur réelle de
alice.firstOccurrenceOfMadHatter.
On dirait que j'ai fait
une faute de majuscule.
Bon, voyons ce que cela
nous donne réellement.
La valeur réelle est -1.
Cela ne ressemble pas à un endroit.
Il ne devrait pas y avoir
un caractère -1 dans le livre.
Regardons la documentation.
Dans mon navigateur,
je cherche java 7 string
et trouve la documentation officielle.
Et puis je cherche la méthode index of.
Méthodes, index of,
nous lui donnons une chaîne.
D'accord, renvoie l'index dans cette chaîne
de la première occurrence
de la sous-chaîne spécifiée
comme nous nous y attendions.
L'index renvoyé est
la plus petite valeur, k,
pour laquelle ce point
commence par stir, virgule, k.
Pas sûre ce que ça signifie,
nous pouvons y réfléchir plus tard.
Si aucune valeur de k n'existe
alors -1 est renvoyé.
Ok, donc -1 signifie qu'il
n'y a pas de mention
du Chapelier Fou comme dans le livre.
Cela pourrait être surprenant.
Le Chapelier Fou est
un personnage célèbre.
Mais il se trouve que dans le livre,
il est toujours appelé
le Chapelier, pas le Chapelier Fou.
文字数を得るメソッドのあとに
他のメソッドを追加します
ファクトシートを見ると
indexOfメソッドが役に立つことが分かります
bookText.indexOf(“Mad hatter”)を返します
テストプログラムに行を追加しましょう
BookTesterは
alice.firstOccurenceOfMAdHatterの
実行結果を出力します
間違えたようです
では実際に何が出力されるか見てみましょう
実行結果は−1になりました
これは位置に見えませんね
-1が本の中にあるはずがありません
ブラウザでドキュメントを見てみましょう
“java 7 string”を検索して
公式ドキュメントを見つけましょう
indexOfメソッドを探します
このメソッドには文字列を与えます
指定した部分文字列が
最初に見つかった文字列内の
インデックス番号を返します
予測どおりです
返ってきたインデックスは
最小値this.startsWith(str,k)のkです
意味はよく分かりませんがあとで考えます
kの値が存在しない時-1が返されるので
-1は本の中にMad Hatterが
出てこないことを意味します
これは意外かもしれませんね
Mad Hatterは有名な登場人物ですが
この本では常にHatterと呼ばれていることが
分かりました
getNumCharacters 메소드 다음에 또 다른 메소드를 추가하겠습니다.
참고 자료를 보시면 indexOf 메소드가 우리를 도와줄 수 있다는 것을 알 수 있습니다.
bookText.indexOf('Mad Hatter')를 리턴하고 싶습니다. 이걸
테스트 프로그램에 넣어서 Alic.firstOccurenceOfMadHatter의
값을 출력 하도록 합니다.
무엇을 출력하는지 봅시다. 이상하게 실제 값이 음수가 나옵니다.
결과가 위치를 알리는 것 같지는 않습니다. 책 안에 -1개의 문자가
있을 수가 없습니다. 문서를 한 번 봅시다. 저는 자바 7 String을 검색해서
공식 문서를 찾아보겠습니다.
그리고 IndexOf 메소드를 찾겠습니다. 이 메소드는 받은 문자열과
매개변수로 받은 문자열을 이용해서 매개변수가 처음 발견된 위치를
알려줍니다. 우리가 찾는 내용입니다. '리턴한 인덱스의 가장 작은
값인 k.' 이것이 지금은 무슨 뜻인지는 모르겠지만
나중에 천천히 알아 보겠습니다. 만약에 찾는 값이 없다면,
-1을 리턴 합니다.' 맞습니다, 그래서 -1의 뜻은 이 책에서 Mad
Hatter의 값이 없다는 뜻입니다. 조금 놀라울 수 있습니다.
Mad Hatter는 유명한 캐릭터 입니다. 하지만 이 책에서는
Mad Hatter가 아닌 Hatter라 불리나 봅니다.
Sau khi có getNumCharacters method, tôi sẽ thêm 1 method nữa.
Ở fact sheet ta có thể thấy indexOf method có thể giúp ta. Ta muốn
return bookText.indexOf("Mad hatter"); Giờ ta cần thêm dòng này vào test program,
Book Tester, cái mà sẽ in ra giá trị thực sự
của Alice.firstOccurenceOfMadHatter, có vẻ tôi đã viết hoa nhầm chỗ này.
Được rồi, hãy xem nó thực sự là gì. Á đù, actual value là -1.
Nghe có vẻ không phải là vị trí của cái gì đó. Chả có vị trí -1 nào
trong quyển sách cả. Hãy xem documentation. Trong trình duyệt của tôi,
tôi sẽ tìm "Java 7 string", và tìm cái documentation chính chủ. Và sau đó
tôi sẽ tìm indexOf method. Methods, indexOf, ta sẽ cho nó 1 string.
Được rồi. "returns the index within this string of the first occurrence
of the specified substring". Đó là những gì ta muốn. Giá trị được trả về
là giá trị bé nhất, k, mà this.startsWith(str,k). Cũng chả rõ
nó có ý nghĩa gì, ta có thể nghĩ sau. Nếu không có giá trị nào được ttìm thấy.
Thì -1 được return. Okay, nên -1 nghĩa là không có cái gì
gọi là "Mad Hatter" được viết trong cuốn sách này. Nghe có vẻ ngạc nhiên.
Mad Hatter là một nhân vật nổi tiếng. Nhưng mà, trong cuốn sách này, anh ấy
chỉ được gọi là Hatter, ko phải Mad Hatter.