切換
舊版
前往
大廳
主題

Java Programming Lesson 07

ジャネス | 2011-08-03 14:17:25 | 巴幣 0 | 人氣 288

Java言語プログラミングレッスン上巻

★★★★★

第07章:while文とString型

while文の構造

while ( 条件式 ) {
  繰り返す処理
}

While1.java(whileの例)
----------
public class While1 {
  public static void main(String[] args) {
    int i = 0;
    while (i <
----------
画面に
javac While1.java
java While1

0
1
2
end
----------

Copy1.java(入力を出力にコピーするプログラム)
----------
import java.io.*;

public class Copy1 {
  public static void main(String[] args) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    try {
      String line = reader.readLine();
      while (line != null) {
        System.out.println(line);
        line = reader.readLine();
      }
    } catch (IOException e) {
      System.out.println(e);
    }
  }
}
----------
画面に
javac Copy1.java
java Copy1

abc
abc
12345
12345
This is Japan.
This is Japan.
私は結城です。
私は結城です。
^Z
----------

キーボードから「入力の終わり」を指定するには
。Windowsの場合には、「Ctrl」+「Z」を押す
。UNIXの場合には、「Ctrl」+「D」を押す

記号<を使うと、標準入力がファイルに切り替わります

----------
画面に
java Copy1.java > input.txt
abc
12345
This is Japan.
私は結城です。
^Z

type input.txt
abc
12345
This is Japan.
私は結城です。a
----------

Copy2.java(複雑な条件式を持ったwhile文)
----------
import java.io.*;

public class Copy2 {
  public static void main(String[] args) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    try {
      String line;
      while ((line = reader.readLine()) != null) {
        System.out.println(line);
      }
    } catch (IOException e) {
      System.out.println(e);
    }
  }
}
----------
画面に
javac Copy2.java
java Copy2

abc
abc
12345
12345
This is Japan.
This is Japan.
私は結城です。
私は結城です。
^Z
----------

CopyLower.java(大文字を小文字に変換するプログラム)
----------
import java.io.*;

public class CopyLower {
  public static void main(String[] args) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    try {
      String line;
      while ((line = reader.readLine()) != null) {
        String s = line.toLowerCase();
        System.out.println(line);
      }
    } catch (IOException e) {
      System.out.println(e);
    }
  }
}
----------
画面に
javac CopyLower.java
java CopyLower

abc
abc
ABC
abc
AbCdEfG
abcdefg
This is Japan.
this is japan.
日本語
日本語
ABC
abc
This is Japan.
this is japan.
^Z
----------

String Class Method Examples
メソッド                    動作
----------------------- ------------------
String replace(char oldChar, char newChar)   文字列のoldCharをすべてnewCharに
                        置換した新しい文字列を返す
String substring(int beginIndex )        文字列のbeginIndex番目の文字以降
                        からなる新しい文字列を返す
String substring(int beginIndex, int endIndex ) 文字列のbeginIndex番目~endIndex -1
                        番目の文字からなる新しい文字列を返す
String toLowerCase()              文字列中の大文字をすべて小文字に
                        変換した新しい文字列を返す
String toUpperCase()              文字列中の小文字をすべて大文字に
                        変換した新しい文字列を返す
String toString()                文字列自体を返す
String trim()                  文字列の両端からホワイトスペースを
                        取り除いた新しい文字列を返す
----------------------- ------------------

Convert1.java(句読点変換)
----------
import java.io.*;

public class Convert1 {
  public static void main(String[] args) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    try {
      String line;
      while ((line = reader.readLine()) != null) {
        String s = line.replace('。', '.');
        s = s.replace('、', ',');
        System.out.println(s);
      }
    } catch (IOException e) {
      System.out.println(e);
    }
  }
}
----------
画面に
javac Convert1.java
java Convert1

abc
abc

,
、。、。、。
,.,.,.
こんにちは、こんにちは。
こんにちは,こんにちは.
おもしろいですか、おもしろいですね。
おもしろいですか,おもしろいですね.
^Z
----------

ガーベッジコレクション(ゴミ集め)
。ゲーベッジを集めてメモリを空ける処理

Find1.java(文字列の検索、Systemを含む行を表示している)
----------
import java.io.*;

public class Find1 {
  public static void main(String[] args) {
    if (args.length != 1) {
      System.out.println("使用法:java Find1 検索文字列 < 検索対象ファイル");
      System.out.println("例:java Find1 System < Find1.java");
      System.exit(0);
    }
    String findstring = args[0];
    System.out.println("検索文字列は「" + findstring + "」です。");
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    try {
      String line;
      int linenum = 1;
      while ((line = reader.readLine()) != null) {
        int n = line.indexOf(findstring);
        if (n >= 0) {
          System.out.println(linenum + ":" + line);
        }
        linenum++;
      }
    } catch (IOException e) {
      System.out.println(e);
    }
  }
}
----------
画面に
javac Find1.java
javac Find1 System < Find1.java

検索文字列は「System」です。
6:       System.out.println("使用法:java Find1 検索文字列 < 検索対象ファ
イル");
7:       System.out.println("例:java Find1 System < Find1.java");
8:       System.exit(0);
11:   System.out.println("検索文字列は「" + findstring + "」です。");
12:   BufferedReader reader = new BufferedReader(new InputStreamReader(System.
in));
19:               System.out.println(linenum + ":" + line);
24:      System.out.println(e);
----------

演算子の優先順位

優先順位 演算子
---- ------------------
高    () []
↑    ++ -- ~ ! - instanceof
|    * /
|    + -
|    >> >>> <<
|    > >= < <=
|    == !==
|    &
|    ^
|    |
|    &&
|    ||
↓    ?:
低    = -= *= /= %= &= ^= |= <<= >>= >>>=
---- ------------------

型を変換(キャスト)する

型変換
→    boolean  byte short  char  int  long  float double
     1-bit  8-bit 16-bit 16-bit 32-bit 64-bit 32-bit 64-bit
---- ---- --- --- --- --- --- --- ---
boolean ■■■■  ×   ×   ×   ×   ×   ×   ×
byte    ×  ■■■  ○   △   ○   ○   ○   ○
short    ×   △  ■■■  △   ○   ○   ○   ○
char    ×   △   △  ■■■  ○   ○   ○   ○
int     ×   △   △   △  ■■■  ○   ●   ○
long    ×   △   △   △   △  ■■■  ●   ●
float    ×   △   △   △   △   △  ■■■  ○
double   ×   △   △   △   △   △   △  ■■■
---- ---- --- --- --- --- --- --- ---
○ 自動変換
● 変換可能だが情報が失われる場合がある
△ 変換にはキャストが必要
× 変換できない

文字列検索関連のStringクラスのメソッド

String str = "Javaは楽しいですか?Javaマスターになりましょう。";
index   :検索する位置
ch    :検索する文字
str    :検索する文字列
fromIndex :検索を開始する位置
--------------------------------
char charAt(int index )
。指定の位置にある文字を返す
int indexOf(int ch)
。文字列のはじめから探す、指定した文字の見つかった位置
int lastIndexOf(int ch)
。文字列の終わりから探す、指定した文字の見つかった位置
int indexOf(int ch, int fromIndex )
。文字列のはじめから指定した位置から検索を開始し、指定した文字の見つかった位置
int lastIndexOf(int ch, int fromIndex )
。文字列の終わりから指定した位置から検索を開始し、指定した文字の見つかった位置
int indexOf(String s)
。文字列のはじめから探す、指定した文字列の見つかった位置
int lastIndexOf(String s)
。文字列の終わりから探す、指定した文字列の見つかった位置
int indexOf(String s, int fromIndex )
。文字列のはじめから指定した位置から検索を開始し、指定した文字列の見つかった位置
int lastIndexOf(String s, int formIndex )
。文字列の終わりから指定した位置から検索を開始し、指定した文字列の見つかった位置
int compareTo(String anotherString) 
。2つの文字列を辞書的に比較します
 。文字列が等しい場合は0を返し
 。文字列が文字列引数以前にある場合は負(0未満)の値を返す
 。文字列が文字列引数以後にある場合は正(0以上)の値を返す
boolean equals(Object anObject)
。文字列を文字列引数と比較して、等しいときにtrueを返す
boolean equalsIgnoreCase(String aString)
。文字列を文字列引数と比較して、大文字小文字の違いを無視する、等しいときにtrueを返す
boolean regionMatches(int inex, String anotherString, int anotherIndex, int len)
。2つの文字領域を比較して、等しいときにtrueを返す
boolean regionMatches(boolean ignoreCase, int inex, String anotherString, int anotherIndex, int len)
。2つの文字領域を比較して、大文字小文字の違いを無視する、等しいときにtrueを返す
boolean startsWith(String prefix, int index )
。この文字列が指定の文字列(prefix)から始まるなら、trueを返す
boolean startsWith(String prefix )
。この文字列が指定の文字列(prefix)から始まるなら、大文字小文字の違いを無視する、trueを返す
boolean endsWith(String suffix )
。この文字列がしての文字列(suffix)で終わるなら、trueを返す
--------------------------------

do-while文の構造
。while 文  0回以上の繰り返し
。do-while文 1回以上の繰り返し

do {
  繰り返す処理
} while ( 条件式 );

break文で繰り返しの中断

while文の中のbreak文

while (...) {
  ...
  if (条件式) {
г----- break;
|  }
|  ...
|}
∟→

for文の中のbreak文

for (int i = 0; i < 100; i++)
  ...
  if (条件式) {
г----- break;
|  }
|  ...
|}
∟→

二重ループとbreak文

while (...) {
  while (...) {
    if (条件式) {
г---------- break;
|    }
|    ...
|  }
∟→...
}

二重ループから一気に脱出するラベル付break文

outer:
  while (...) {
    while (...) {
      if (条件式) {
г------------- break outer;
|      }
|    }
|  }
∟→

switchの中のbreak文

for (int i = 0; i < 100; i++) {
  ...
  switch (c) {
  case 'a':
    ...
    break;
  case 'b':
    ...
г----- break;
|  default:
|    ...
|    break;
|  }
∟→ ...
}

continue文で繰り返しを次に進む

    ┌----------┐
while (...) {    |
  ...       |
  if (条件式) {  |
    continue; →┘
  }
  ...
}

ラベル付きcontinue文

outer:   ┌--------------------┐
  while (...) {         |
    while (...) {       |
      if (条件式) {     |
        continue outer; →┘
      }
    }
  }

学んだこと
。while文
。String型
。break文
。continue文

練習問題7-1

次のwhile文について書かれた文章のうち、正しいものに○、誤っているものに×を付けてください

int n = 10;
while (n > 0) {
  System.out.println(n);
  n = n - 1;
}

(1) 10 から 0 までの 11 個の数字が表示される
  ×
  (11回目のとき、n = 0、while文の条件式 n > 0 でfalse、表示されなくて終わる)
(2) while文の {} に入った直後、必ず n > 0 は true である。
  ○
(3) 条件式 n > 0 は 11 回評価される。
  ○
(4) 式 n > 0 の型は int型である。
  ×
  (式 n > 0 の型はboolean型です)
(5) もしも、
  n = n - 1;
  を間違えて、
  n = n + 1;
  と書いてしまったら、この while文は永遠にとまらない。
  ×
 (int の最大値は2147483647になります。それに1を加えると、オーバーロードを起こし、)
 (-2147483648になります。それで、n > 0 ではないので、while文は終了します。)

練習問題7-2

for文を使ったプログラムを、while文だけを使うように修正してください。

Graph1.java(for文を使ったプログラム)
----------
public class Graph1 {
  public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
      for (int j = 0; j < i * i; j++) {
        System.out.print("*");
      }
      System.out.println("");
    }
  }
}
----------
画面に
javac Graph1.java
java Graph1


*
****
*********
****************
*************************
************************************
*************************************************
****************************************************************
*********************************************************************************
----------

Graph2.java(while文を使ったプログラム)
----------
public class Graph2 {
  public static void main(String[] args) {
    int i = 0;
    while (i < 10) {
      int j = 0;
      while (j < i * i) {
        System.out.print("*");
        j++;
      }
      System.out.println("");
      i++;
    }
  }
}
----------
画面に
javac Graph2.java
java Graph2


*
****
*********
****************
*************************
************************************
*************************************************
****************************************************************
*********************************************************************************
----------

練習問題7-3

MakeHtml.java(txtファイルを読み取ってhtmlファイルを出すプログラム)
----------
import java.io.*;

public class MakeHtml {
  public static void main(String[] args) {
    BufferedReader reader = new BufferedReader (new InputStreamReader (System.in));
    try {
      String line;
      // ルール1
      System.out.println("");
    while ((line = reader.readLine()) != null) {
      // ルール3
      if (line.startsWith("■")) {
        System.out.println("

" + line.substring(1) + "

");
      // ルール4
      } else if (line.startsWith("●")) {
        System.out.println("

" + line.substring(1) + "

");
      // ルール5
      } else if (line.startsWith("----")) {
        System.out.println("

");
      // ルール6
      } else if (line.startsWith("address")) {
        System.out.println("hyuki@example.com");
      // ルール7
      } else {
        System.out.println(line);
      }
    }
      // ルール2
      System.out.println("");
    } catch (IOException e) {
        System.out.print(e);
    }
  }
}
----------
画面に
javac MakeHtml.java
java MakeHtml < hello.txt > hello.html
----------

hello.txt(入力ファイル)
----------
■私のホームページへようこそ
----
●こんにちは
こんにちは! 私のホームページへようこそ。
----
●自己紹介
私は結城浩といいます。どうぞよろしく。
----
●メール待っています
あなたからのメールをお待ちしています。
メールアドレスは、
address
です。
----------

hello.html(出力ファイル)
----------

私のホームページへようこそ




こんにちは


こんにちは! 私のホームページへようこそ。


自己紹介


私は結城浩といいます。どうぞよろしく。


メール待っています


あなたからのメールをお待ちしています。
メールアドレスは、
hyuki@example.com
です。

----------

出力ファイルをWebブラウザで見た様子
----------
私のホームページへようこそ

こんにちは

こんにちは! 私のホームページへようこそ。
自己紹介

私は結城浩といいます。どうぞよろしく。
メール待っています

あなたからのメールをお待ちしています。 メールアドレスは、 hyuki@example.com です。
----------

練習問題7-4

ContinueTest.java(入力した文字列が、"{" または "}" で終わるときだけ標準出力する)
----------
import java.io.*;

public class ContinueTest {
  public static void main(String[] args) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    try {
      String line;
      while ((line = reader.readLine()) != null) {
        if (!line.endsWith("{") && !line.endsWith("}")) {
          continue;
        }
        System.out.println(line);
      }
    } catch (IOException e) {
      System.out.println(e);
    }
  }
}
----------
画面に
javac ContinueTest.java
java ContinueTest

abc{
abc{
def}
def}

Ctrl-C
----------

ContinueTest1.java(Continueを使わない)
----------
import java.io.*;

public class ContinueTest1 {
  public static void main(String[] args) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    try {
      String line;
      while ((line = reader.readLine()) != null) {
        if (line.endsWith("{") || line.endsWith("}")) {
          System.out.println(line);
        }
      }
    } catch (IOException e) {
      System.out.println(e);
    }
  }
}
----------
画面い
javac ContinueTest1.java
java ContinueTest1

abc{
abc{
def}
def}

Ctrl-C
----------

★★★★★

第7章終わり

創作回應

相關創作

更多創作