Java:本体がないfor文を書いた
Common Lispのdoマクロなどは本体なしループとかでもあんまし違和感ないけど、Javaで書いてみたらキモイ
プログラミング言語Java↓の練習問題13.1をみて本体なしのforループ書けそうだと思ったので回答を考えた。
プログラミング言語Java (The Java Series)
- 作者: ケン・アーノルド,ジェームズゴスリン,デビッドホームズ,柴田芳樹
- 出版社/メーカー: ピアソンエデュケーション
- 発売日: 2007/04
- メディア: 単行本
- 購入: 38人 クリック: 1,044回
- この商品を含むブログ (71件) を見る
文字列中に、指定された文字が出現する回数を数えるメソッドを書きなさい。
書いた。
public class Test { public static void main(String[] args) { String s = "A good glass in the bishop's hostel in the devil's seat" + "forty-one degrees and thirteen minutes northeast and by north" + "main branch seventh limb east side shoot from the left eye of the death's-head" + "a bee line from the tree through the shot fifty feet out."; char c = 'e'; int n = 0; for (int i = 0; 0 <= i; n += 0 <= (i = s.indexOf(c, ++i)) ? 1 : 0) ; System.out.println(n + "個あった。"); } }
33個あった。
sの内容はポーの黄金虫の暗号文。