教科書の3.5節を読んで、 ユーザモデルとデザインモデル(設計者のモデル)について理解しておいてください(36ページから40ページ)。 この部分を授業で説明した資料を以下に置いておきます。
皆さんは、自分が作ったプログラムを人に使ってもらった時に、 思いもしないようなバグを発見してもらった経験がありますでしょうか? 他人は、 プログラムを作った自分だったら絶対に行わないような操作をやってしまいます。 そこで、
10月30日の福地先生講義は延期になり、通常授業になります。
学籍番号 1840702 1840706 1840708 1840709 1840710 1840644 (聴講) 1840645 2018年11月6日 1840648 1840649 2018年11月6日 1840651 1840655 1840658 1840659 1840661 1840662 1840663 1840665 1840669 1840673 2018年11月6日 1840675 1840677 1740671
JLabelのところをJButtonにしてみましょう
解答例:
import javax.swing.*;
import java.awt.*;
public class SimpleWindow extends JFrame {
public void initialize () {
this.setTitle("私が作った最初の窓");
JButton button = new JButton("Hello!");
Container container = this.getContentPane();
container.add(button);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String argv[]) {
SimpleWindow sw = new SimpleWindow();
sw.initialize();
}
}
http://www.siio.jp/index.php?plugin=attach&pcmd=open&file=button.png&refer=How2JavaProgramming
プログラム12.2をみてください。 getContentPane()で得られたContainerに直接ボタンを貼付けることもできますが、 貼付けられるのは一つのボタンだけのようです。 そこで、JPanel (パネル) に2個のボタンを貼付け、それをContainerに貼付けることで複数のボタンを表示しています。
プログラム12.2を参考にして、継承を使ったプログラムによるウィンドウの中に、 2個のボタンを出してみよう。
解答例:
import javax.swing.*;
import java.awt.*;
public class SimpleButton extends JFrame {
public void initialize () {
this.setTitle("私が作った最初の窓");
JPanel panel = new JPanel();
JButton button1 = new JButton("button1");
JButton button2 = new JButton("button2");
panel.add(button1);
panel.add(button2);
Container container = this.getContentPane();
container.add(panel);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String argv[]) {
SimpleButton sw = new SimpleButton();
sw.initialize();
}
}
このプログラムでは,ボタンを押しても何もおこりません.
ボタンが押されたイベントを受け取るためには,
プログラム12.3を参考に,ボタンを押したらprintlnで次のようなメッセージを表示するプログラムを作ってみましょう.
ヒント(最初の6行です)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleButton extends JFrame implements ActionListener {
JButton button1, button2;
public void initialize () {
解答例
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleButton extends JFrame implements ActionListener {
JButton button1, button2;
public void initialize () {
this.setTitle("私が作った最初の窓");
JPanel panel = new JPanel();
button1 = new JButton("button1");
button2 = new JButton("button2");
button1.addActionListener(this);
button2.addActionListener(this);
panel.add(button1);
panel.add(button2);
Container container = this.getContentPane();
container.add(panel);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed (ActionEvent e) {
if(e.getSource()==button1)
System.out.println("Hello");
else
System.out.println("Goodbye");
}
public static void main(String argv[]) {
SimpleButton sw = new SimpleButton();
sw.initialize();
}
}
ここではボタンを区別するために、インスタンス(への参照)を比較した。それ以外の方法もある。 一つは、ボタンのテキストを入手することである。ボタンのテキストを入手してそれを比較しても良い。 ボタンのテキストを表示するだけなら以下のようにしても良い。
public void actionPerformed(ActionEvent e){
System.out.println(((JButton)e.getSource()).getText());
}
もう一つは、ボタンにコマンドを書く方法である。 ボタンにsetActionCommand(String)を定義しておくと、getActionCommand()で知ることができる。
button1.setActionCommand("hello");
としておけば、actionPerformedの中で
e.getActionCommand();
で文字列を得られる。例えば、
public void actionPerformed(ActionEvent e){
System.out.println(e.getActionCommand());
}
でコマンド部分を印刷できる。
上で作った二つのボタンのプログラムに対して、レイアウトマネージャのFlowLayoutを使って、左寄せ、センタリング、右寄せを試してください。
演習のヒント
bt1 = new JButton("button1");
bt2 = new JButton("button2");
panel.setLayout(new FlowLayout(FlowLayout.RIGHT));
bt1.setActionCommand("this is b1");
bt2.setActionCommand("this is b2");
FlowLayoutにはCENTER, LEFT, RIGHTなどの揃え方の指定がありますが、これをコンストラクタの引数で指定できるようです。addのところではレイアウト指定しないようです。
本日作ったボタンを二つ表示するプログラム(どのバージョンでも良いです)のjava, classを、いつものように学籍番号+ローマ字名前のフォルダに入れて、圧縮して提出してください。
ヒント:プログラム12.4を見て、上記のプログラムを拡張して5個のボタンに対応して, WEST, EAST, SOUTH, NORTH, CENTERと表示されるプログラム作るとわかりやすいかもしれません。そうすれば、プログラム13.1のボタンの名前を表示するプログラムが作りやすいと思います。次回の授業で提出お願いします。
なお、以下のようにすると、ボタンの名前を印刷することができます。
public void actionPerformed(ActionEvent e){
System.out.println(((JButton)e.getSource()).getText());
}
http://docs.oracle.com/javase/jp/8/docs/api/index.html
/home/isstaff/siio/Public/Drop Box/.に提出してください。ターミナル.appからなら
cp 123456siioitiro.zip /home/isstaff/siio/Public/Drop\ Boxとしてください。ファインダーからなら、メニューから「移動」「フォルダへ移動...」を選んで 以下のように入力して、移動ボタンを押して、そこに現れるドロップボックスホルダに、ドラッグアンドドロップしてください。
http://www.amazon.co.jp/dp/4883732258/
買ってください。もしくは、先輩から安く譲ってもらってください。
こちらからダウンロードできます。 演習室のOSにあわせたバージョンをダウンロードして~/Applicationsにコピーします。
https://coteditor.com/archives.ja
class Hello {
public static void main (String args[]) {
System.out.println("hello java world!");
}
}
javac Hello.java (コンパイルする) java Hello (実行する。.javaなどの拡張子は不要) hello java world! (結果)
授業の最後の方で紹介する,Swingというフレームワークを使ってウィンドウを出してみます.
import javax.swing.JFrame;
public class SimpleWindow {
public static void main(String argv[]) {
JFrame f = new JFrame("私が作った最初の窓");
f.setSize(200,100);
f.setVisible(true);
}
}
これをSimpleWindow.javaという名前で保存して、
javac SimpleWindow.java java SimpleWindow
とタイプしてコンパイル/実行します。 このプログラムは,ウィンドウのクローズボタンを押しても終了しません. プログラムを停止するには,ターミナルでコントロール-cを押します.
ヒント
class ArgsTest {
public static void main (String args[]) {
System.out.println(args[0]);
}
}
解答
class ArgsTest {
public static void main (String args[]) {
System.out.println(args[0] + " + " + args[1]);
}
}
乱数を10個表示する
public class Score {
public static void main (String argv[]) {
int i,a;
for(i=0;i<10;i++) {
a=(int)(Math.random() * 100);
System.out.println(a);
}
}
}
次にこの乱数を点数とみなして、演習問題5.4の基準に従ってABCDを表示するプログラムを書け。 動作例を以下に示す。
解答例:
public class Score {
public static void main (String argv[]) {
int i,a;
for(i=0;i<10;i++) {
a=(int)(Math.random() * 100);
System.out.print(a + " ");
if(a<40) System.out.println("D");
else if(a<60) System.out.println("C");
else if(a<80) System.out.println("B");
else System.out.println("A");
}
}
}
解答例:
class Kinri {
public static void main (String args[]) {
double okane=100000;
int year;
year=1;
while(okane < 200000) {
okane = okane * 1.05;
System.out.println("year = " + year + " okane= " + okane);
year++;
}
}
}
現在の普通預金の金利0.001%だと倍になるのに何年かかるだろうか。確かめてみよう。
while文をfor文に変えてみる
解答例:
class Kinri {
public static void main (String args[]) {
double okane=100000;
int year;
for(year=1;okane < 200000; year++) {
okane = okane * 1.05;
System.out.println("year = " + year + " okane= " + okane);
}
}
}
class ArrayTest {
public static void main (String args[]) {
int[] vec = new int[3];
vec[0]=1;
vec[1]=2;
vec[2]=3;
for (int x: vec) {
System.out.println(x);
}
}
}
mainの引数argsは、Stringの配列で、コマンドラインで起動したとき、 コマンドの後に続けた書いた文字が入っています。 args[0], args[1], args[2] .... をすべてfor-each文で 表示するプログラムを書いてみましょう。
ヒント:for(String s: args)を使います
class ArgsTest2 {
public static void main (String args[]) {
for(String s: args)
System.out.println(s);
}
}
ArgsTest2.javaとArgsTest2.classを出席番号+ローマ字名前のフォルダに入れて、圧縮して提出してください。
今作ったTestPoint3D.javaを変更して
ようにしてください。 この結果、以下のような実行結果が出るようにしてください
public class Point {
private int x, y;
void set(int newx, int newy) {x=newx; y=newy;}
int getx() { return x;}
int gety() { return y;}
void print () {
System.out.println(x + ", " + y);
}
public static void main(String argv[]) {
Point pt1= new Point();
Point pt2 = new Point();
pt1.set(10,20);
pt2.set(-pt1.getx(), -pt1.gety());
pt1.print();
pt2.print();
}
}
10, 20, 30 -10, -20, -30
という結果が出るようにしましょう
public static void main(String argv[]) {
Point3D pt1 = new Point3D();
Point3D pt2 = new Point3D();
pt1.set(10, 20, 30);//インスタンス変数を設定
pt2.set(-pt1.getx(), -pt1.gety(), -pt1.getz());
pt1.print();//インスタンスメソッド呼出
pt2.print();
}
10, 20, 30 -10, -20, -30 74.83314773547883
という結果が出るようにしましょう
public static void main(String argv[]) {
Point3D pt1 = new Point3D();
Point3D pt2 = new Point3D();
pt1.set(10, 20, 30);//インスタンス変数を設定
pt2.set(-pt1.getx(), -pt1.gety(), -pt1.getz());
pt1.print();//インスタンスメソッド呼出
pt2.print();
System.out.println(pt1.distance(pt2));
}
double distance ( int ptx, int pty, int ptz ) {
int dx = ptx - this.x;
int dy = pty - this.y;
int dz = ptz - this.z;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
double distance ( Point3D p ) {
return this.distance(p.getx(), p.gety(), p.getz());
}
Point3D.javaとPoint3D.classを出席番号+ローマ字名前のフォルダに入れて、圧縮して提出してください。
次回は休講ですので再来週11/8の授業の最初に回収します。
public static void main(String argv[]) {
Osaifu saifu1 = new Osaifu();
Osaifu saifu2 = new Osaifu();
saifu1.in(1000);
saifu2.in(500);
saifu1.print();
saifu2.print();
saifu2.in(saifu1.out(200));
saifu1.print();
saifu2.print();
}
public class Osaifu {
int okane;
public void in (int x) { okane += x; }
public int out(int x) { okane -= x; return x; }
public void print() {
System.out.println( "okane = " + okane +" yen");
}
public static void main(String argv[]) {
Osaifu saifu1 = new Osaifu();
Osaifu saifu2 = new Osaifu();
saifu1.in(1000);
saifu2.in(500);
saifu1.print();
saifu2.print();
saifu2.in(saifu1.out(200));
saifu1.print();
saifu2.print();
}
}
public int out(int x) {
if(x < okane ) {
okane = okane -x;
return x;
} else {
int nokori = okane;
okane =0;
return nokori;
}
}
ことができるコンストラクタを作ろう。
これをmainから呼んで、上記のプログラムと同じことをするためには、
Osaifu saifu1 = new Osaifu(1000);//インスタンスを作る //最初の保持金額を1000円にする Osaifu saifu2 = new Osaifu(500);//インスタンスを作る //最初の保持金額を500円にする
とすることになる。
以下のコンストラクタを作ることになる。
Osaifu() { okane = 0; }
Osaifu(int x) { okane = x; }
これは以下のように書いても良い。
Osaifu() { this(0); }
Osaifu(int x) { okane = x; }
継承の話をしました。 別のクラスを継承することで、 差分だけを書いて機能を拡張していくことができます。
public class OsaifuUSD extends Osaifu {
public static void main(String argv[]) {
OsaifuUSD saifu1= new OsaifuUSD();
OsaifuUSD saifu2=new OsaifuUSD();
saifu1.in(1000);
saifu2.inUSD(5);
saifu1.print();
saifu2.print();
saifu2.inUSD(saifu1.outUSD(2));
saifu1.print();
saifu2.print();
}
public class OsaifuUSD extends Osaifu {
public int outUSD(int usd) {
okane-=usd * 90;
return usd;
}
public void inUSD(int usd) {
okane+=usd * 90;
}
public static void main(String argv[]) {
OsaifuUSD saifu1 = new OsaifuUSD();
OsaifuUSD saifu2 = new OsaifuUSD();
saifu1.in(1000);
saifu2.inUSD(5);
saifu1.print();
saifu2.print();
saifu2.inUSD(saifu1.outUSD(2));
saifu1.print();
saifu2.print();
}
}
親のメソッドを活用しても良い
public class OsaifuUSD extends Osaifu {
public int outUSD(int usd) {
return ( out( use * 90) / 90 );
}
public void inUSD(int usd) {
in( usd * 90 );
}
…
}
親のメソッドを呼ぶことを明示的に書くためにsuper.をつかってもよい。
public class OsaifuUSD extends Osaifu {
public int outUSD(int usd) {
return ( super.out( use * 90) / 90 );
}
public void inUSD(int usd) {
super.in( usd * 90 );
}
…
}
以下のプログラムの中で、 クラス、インスタンス、サブクラス、スーパクラス、クラスメソッド、インスタンスメソッドがどれであり、 インスタンス化、継承がどこで行われているのか確認してください。 (importで始まる一行目はまだ説明していない内容なので小テストでは扱いません。無視してください)
import javax.swing.JFrame;
public class SampleWindow extends JFrame {
public static void main(String args[]) {
SampleWindow w = new SampleWindow();
w.setVisible(true);
}
}
次のプログラムを作って試してください。 引数が少ないとエラーが出るのを確認してください。
public class TestException {
public static void main(String argv[]){
System.out.println(argv[0]+" "+argv[1]);
System.out.println("Nice to meet you.");
}
}
エラーが出る可能性のある場所をtryでくくっておき、 エラーが出たらそれを捕捉する処置をcatchで指定します。
public class TestException {
public static void main(String argv[]){
try{
System.out.println(argv[0]+" "+argv[1]);
System.out.println("Nice to meet you.");
}
catch (Exception e) {
System.out.println("please input 2 words.");
}
}
}
public class TestString {
public static void main(String argv[]) {
System.out.println(argv[0]);
}
}
[e100:?/Documents/java] siio% java TestString ochanomizu ochanomizu uzimonahco [e100:?/Documents/java] siio%
さらには、引数がない場合は引数入力を促すことを表示してみよう。
[e100:?/Documents/java] siio% java TestString please input a word [e100:?/Documents/java] siio%
このソースは、
public class TestString {
public static void main (String argv[]) {
try{
System.out.println(argv[0]);
int len = argv[0].length();
for(int i = len - 1; i>=0; i--) {
System.out.print(argv[0].charAt(i));
}
System.out.println();
}
catch (Exception e) {
System.out.println("please input a word");
}
}
}
である。
サンプルプログラムを実行するときは、
LinkedList<String> list = new LinkedList<String>();
などと定義すると良い。
Alice --> Bob --> Cindy --> DaveというLinkedListをつくって、 それからtoArray()メソッドでString配列を作ってfor each文で要素を印刷する
import java.util.*;
public class LinkedListTest{
public static void main(String[] argv) {
LinkedList<String> list = new LinkedList<String>();
list.add("Alice");
list.add("Bob");
list.add("Dave");
list.add("Cindy");
Object[] names = list.toArray();
for(Object s: names ) System.out.println(s);
}
}
プログラム10.4を参考にして、 以下のように動作する英語ー日本語単語変換プログラムを作れ。
[e100:?/Documents/java] siio% java EtoJ banana バナナ [e100:?/Documents/java] siio% java EtoJ apple りんご [e100:?/Documents/java] siio% java EtoJ Please input an English word
ヒント:
import java.util.*;
public class EtoJ{
public static void main(String args[]) {
HashMap<String,String> map = new HashMap<String,String>();
map.put("apple","りんご");
map.put("banana","バナナ");
map.put("orange","みかん");
map.put("pineapple","パイナップル");
map.put("grape","ぶどう");
map.put("peach","もも");
map.put("melon","メロン");
map.put("lemon","レモン");
try {
System.out.println(map.get(args[0]));
}
catch(Exception e) {
System.out.println("Please input an English word");
}
}
}
EtoJ.javaとEtoJ.classを出席番号+ローマ字名前のフォルダに入れて、圧縮して提出してください。
import java.io.*;
public class FoutTest {
public static void main(String[] args) {
try {
FileOutputStream fout = new FileOutputStream("fout.dat");
fout.write(1234);
fout.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}
これでfout.datという名前のファイルができあがるはずです。 作ったファイルを
od -h fout.dat
または
hexdump fout.dat
してみてください
import java.io.*;
public class DoutTest {
public static void main (String[] args) {
try {
FileOutputStream fout = new FileOutputStream("dout.dat");
DataOutputStream dout = new DataOutputStream(fout);
dout.writeInt(100);
dout.close();
}catch (Exception e) {
System.out.println(e);
}
}
}
これでdout.datという名前のファイルができあがるはずです。 作ったファイルを
od -h dout.dat
または
hexdump dout.dat
してみてください
e100:java siio$ hexdump dout.dat 0000000 00 00 00 64 0000004
import java.io.*;
public class DoutTest {
public static void main (String[] args) {
try {
FileOutputStream fout = new FileOutputStream("dout.dat");
DataOutputStream dout = new DataOutputStream(fout);
dout.writeInt(100);
dout.close();
FileInputStream finput = new FileInputStream("dout.dat");
DataInputStream dinput = new DataInputStream(finput);
System.out.println(dinput.readInt());
dinput.close();
}catch (Exception e) {
System.out.println(e);
}
}
}
作ったファイルを
od -h dout.dat
または
hexdump dout.dat
してみてください
解答例
import java.io.*;
public class En111 {
public static void main (String[] args) {
int i;
try {
FileOutputStream fout = new FileOutputStream ("dout.dat");
DataOutputStream dout = new DataOutputStream(fout);
for(i=1;i<101;i++) dout.writeInt(i);
dout.close();
FileInputStream fin = new FileInputStream ("dout.dat");
DataInputStream din = new DataInputStream(fin);
for(i=1;i<101;i++) System.out.println(din.readInt());
din.close();
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
System.out.println(e);
}
}
}
作ったファイルを
od -h
または
hexdump
してみてください
import java.io.*;
public class PrintWriterTest{
public static void main(String[] args) {
try {
//writer.txtというファイルを作って文字を書き込む
FileWriter fwriter = new FileWriter("writer.txt");
PrintWriter pwriter = new PrintWriter(fwriter);
pwriter.println(2006);
pwriter.println("Java教科書");
//fwriter.write("Java教科書");
pwriter.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}
つぎに、プログラム11.4を参考にして、 このPrint Write Testに書き足して、 書き込んだデータを読み出して画面に表示するプログラムを作ってください。
ヒント:
import java.io.*;
public class PrintWriterTest{
public static void main(String[] args) {
try {
//writer.txtというファイルを作って文字を書き込む
FileWriter fwriter = new FileWriter("writer.txt");
PrintWriter pwriter = new PrintWriter(fwriter);
pwriter.println(2006);
pwriter.println("Java教科書");
//fwriter.write("Java教科書");
pwriter.close();
ここに書き足す
}
catch (IOException e) {
System.out.println(e);
}
}
}
import java.io.*;
public class PrintWriterTest{
public static void main(String[] args) {
try {
//writer.txtというファイルを作って文字を書き込む
FileWriter fwriter = new FileWriter("writer.txt");
PrintWriter pwriter = new PrintWriter(fwriter);
pwriter.println("java 教科書" + 2001 );
pwriter.close();
//writer.txtのファイルの中身をSystem.out.printlnで表示する
FileReader freader = new FileReader("writer.txt");
BufferedReader breader = new BufferedReader(freader);
String tmp;
while( (tmp=breader.readLine() ) != null) {
System.out.println(tmp);
}
breader.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}
キーボードから1行入力された文字列によるテキストファイルを作る
ヒント
import java.io.*;
public class En112 {
public static void main(String[] args) {
try {
ここにプログラムを書く
}
catch(IOException e) {
System.out.println(e);
}
}
}
「キーボードから1行入力された文字列によるテキストファイルを作る」プログラムの.javaと.classファイルを、出席番号+ローマ字名前のフォルダに入れて、圧縮して提出してください。
import java.io.*;
public class En112 {
public static void main(String[] args) {
try {
InputStreamReader ireader = new InputStreamReader (System.in);
BufferedReader breaderK = new BufferedReader(ireader);
String line = breaderK.readLine();
FileWriter fwriter = new FileWriter("writer.txt");
PrintWriter pwriter = new PrintWriter(fwriter);
pwriter.println(line);
pwriter.close();
FileReader freader = new FileReader("writer.txt");
BufferedReader breaderF = new BufferedReader(freader);
String tmp=null;
while( (tmp=breaderF.readLine()) != null)
System.out.println(tmp);
breaderF.close();
}
catch(IOException e) {
System.out.println(e);
}
}
}
ヒント1
import java.net.*;
が必要です。
URL targetURL = new URL("http://www.ocha.ac.jp/");
でURLクラスのインスタンスが得られる。
InputStream istream = targetURL.openStream();
でこれからInputStreamのインスタンスが得られる。
InputStreamReader isreader = new InputStreamReader(istream);
でこれからInputStreamReaderのインスタンスが得られる。
BufferedReader breader = new BufferedReader( isreader );
でこれからBufferedReader のインスタンスが得られる。
ヒント2
import java.io.*;
import java.net.*;
public class URLTest {
public static void main (String argv[]) {
try {
ここにプログラムを書く
} catch (IOException e) {
System.out.println("error...");
}
}
}
ヒント3:
import java.io.*;
import java.net.*;
public class URLTest {
public static void main (String argv[]) {
try {
URL targetURL = new URL("http://www.ocha.ac.jp/");
InputStream istream = targetURL.openStream();
InputStreamReader isreader = new InputStreamReader(istream);
BufferedReader breader = new BufferedReader( isreader );
ここで一行ずつ読み込む
} catch (IOException e) {
System.out.println("error...");
}
}
}
解答例:
import java.io.*;
import java.net.*;
public class URLTest {
public static void main (String argv[]) {
try {
URL targetURL = new URL("http://www.ocha.ac.jp/");
InputStream istream = targetURL.openStream();
InputStreamReader isreader = new InputStreamReader(istream);
BufferedReader breader = new BufferedReader( isreader );
String line;
while((line=breader.readLine()) != null) System.out.println(line);
} catch (IOException e) {
System.out.println("error...");
}
}
}
http://siio.jp/cat.jpg
をダウンロードして、cat.jpgというファイルを作るプログラムを作ってください。 データはテキストじゃなくて、バイナリーです。
ヒント1:
ヒント2:
import java.io.*;
import java.net.*;
public class URLJpeg {
public static void main (String argv[]) {
try {
URL targetURL = new URL("http://siio.jp/cat.jpg");
InputStream istream = targetURL.openStream();
FileOutputStream fout = new FileOutputStream("cat.jpg");
というインスタンスを作って、
istream.read()
で読んで、
fout.write(1バイト)
で書き出します。
解答例
import java.io.*;
import java.net.*;
//http://siio.jp/cat.jpg
//をダウンロードして、cat.jpgというファイルを作るプログラム
public class URLJpeg {
public static void main (String argv[]) {
try {
URL targetURL = new URL("http://siio.jp/cat.jpg");
InputStream istream = targetURL.openStream();
FileOutputStream fout = new FileOutputStream("cat.jpg");
int aData;
while((aData = istream.read()) != -1) fout.write(aData);
istream.close();
fout.close();
} catch (IOException e) {
System.out.println("error...");
}
}
}
上記の例では写真データを1バイトずつ読み書きしていました。 InputStreamのメソッドを調べると、複数バイト単位で読み込むメソッドがあります。 たとえば、1024バイトずつ読み書きすることで、処理速度が向上すると期待できます。 そこで、複数バイト読み書きするよう、上記のプログラムを変更して、 実際にどの程度(実行速度にして何倍くらい)性能向上するか確認してみましょう。
read
public int read(byte[] b)
throws IOException
入力ストリームから配列長さだけのバイト数を読み込もうとし、それをバッファ配列 b に格納します。
実際に読み込まれたバイト数は整数として返されます。
戻り値は、バッファに読み込まれたバイトの合計数。ストリームの終わりに達してデータがない場合は -1
を使って読みこみ、
write
public void write(byte[] b,
int off,
int len)
throws IOException
指定された byte 配列の、オフセット位置 off から始まる len バイトを出力ストリームに書き込みます。
を使ってください。
byte[] data = new byte[1024];
という配列を用意して、
int datalength; while(( datalength=istream.read(data)) != -1) fout.write(data, 0, datalength);
とします。
import java.io.*;
import java.net.*;
//http://siio.jp/cat.jpg
//をダウンロードして、cat.jpgというファイルを作るプログラムを作ってください。
//データはテキストじゃなくて、バイナリーです。
public class URLJpeg2 {
public static void main (String argv[]) {
byte[] data = new byte[1024];
try {
URL targetURL = new URL("http://siio.jp/cat.jpg");
InputStream istream = targetURL.openStream();
FileOutputStream fout = new FileOutputStream("cat.jpg");
int datalength;
while(( datalength=istream.read(data)) != -1) fout.write(data, 0, datalength);
istream.close();
fout.close();
} catch (IOException e) {
System.out.println("error...");
}
}
}
ここでは1024バイトを読み込むことにしました。でも、InputStreamのメソッドを見ると、available()というのがあります。
available() この入力ストリームのメソッドの次の呼出しによって、ブロックせずにこの入力ストリームから読み込むことができる(またはスキップできる)推定バイト数を返します。
これを使えば、適切な長さを見積もれるかもしれません。
import javax.swing.JFrame;
public class SimpleWindow {
public static void main(String argv[]) {
JFrame f = new JFrame("私が作った最初の窓");
f.setSize(200,100);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
import javax.swing.JFrame;
public class SimpleWindow extends JFrame {
public void initialize () {
this.setTitle("私が作った最初の窓");
this.setSize(200,100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main (String argv[]) {
SimpleWindow sw = new SimpleWindow();
sw.initialize();
}
}
プログラム12.1を参考にして、上記の、継承を使ったプログラムによるウィンドウの中に、 Hello!という文字を出してみよう。
解答例:
import javax.swing.*;
import java.awt.*;
public class SimpleWindow extends JFrame {
public void initialize () {
this.setTitle("私が作った最初の窓");
JLabel label = new JLabel("Hello!");
Container container = this.getContentPane();
container.add(label);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String argv[]) {
SimpleWindow sw = new SimpleWindow();
sw.initialize();
}
}
JLabelのところをJButtonにしてみましょう
ボタンを出すプログラムのjavaとclassを提出してください。
3/4以上出席してください。(欠席は3回まで)欠席4回で自動的に不可になります。 欠席3回以下なら不可にはなりませんが、成績が下がるかもしれませんので、心当たり無ければ連絡ください。 (病欠、公欠、忌引などは0になっているはずですが間違っていたら連絡ください。)
| 学籍番号 | 10/4 | 10/11 | 10/25 | 11/8 | 11/15 | 11/22 | 合計 |
| 1720501 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720502 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720503 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720504 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720505 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720506 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720507 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720508 | 0 | 1 | 0 | 0 | 0 | 0 | 1 |
| 1720509 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720510 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720511 | 0 | 0 | 1 | 0 | 0 | 1 | 2 |
| 1720512 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720513 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720514 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720515 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720516 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720517 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720518 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720519 | 0 | 0 | 0 | 0 | 0 | 1 | 1 |
| 1720520 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720521 | 1 | 0 | 0 | 0 | 0 | 1 | 2 |
| 1720522 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720523 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720524 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720525 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720526 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720527 | 0 | 0 | 0 | 0 | 1 | 0 | 1 |
| 1720528 | 0 | 0 | 0 | 0 | 0 | 1 | 1 |
| 1720529 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720530 | 1 | 0 | 0 | 0 | 1 | 1 | 3 |
| 1720531 | 0 | 0 | 0 | 0 | 0 | 1 | 1 |
| 1720532 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720533 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720534 | 0 | 0 | 0 | 0 | 0 | 1 | 1 |
| 1720535 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720536 | 0 | 0 | 0 | 0 | 0 | 1 | 1 |
| 1720537 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720538 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720539 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720540 | 0 | 0 | 0 | 0 | 0 | 1 | 1 |
| 1720541 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720542 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1720543 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1620514 | 1 | 1 | 1 | 1 | 1 | 1 | 6 |
| 1520520 | 0 | 1 | 0 | 0 | 1 | 0 | 2 |
| 1740665 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |