| <演習1>の解答例 |
| class Student { String name; // 名前 int no; // 学籍番号 // データをセットする public void setData( String s, int n ){ name = new String( s ); no = n; } public void show(){ System.out.println(" 名前:" + name + ", 学籍番号:" + no ); } } class Ensyu1101 { public static void main(String[] args) { Student st1 = new Student(); Student st2 = new Student(); st1.setData("鈴木", 5401232); st2.setData("佐藤", 3602081); st1.show(); st2.show(); } } |
| <演習2>の解答例 |
| class Ensyu1102 { public static void main(String[] args) { String str1 = "Good "; String str2 = "morning"; String str3 = "evening"; System.out.println( add(str1,str2) ); System.out.println( add(str1,str3) ); } // s1 と s2 を連結して ret で返す static String add( String s1, String s2 ){ StringBuffer sb = new StringBuffer(); sb.append(s1); sb.append(s2); String ret = sb.toString(); return ret; } } |
| <演習3>の解答例 |
| import java.util.Scanner; class Ensyu1103 { public static void main(String[] args) { int cnt = 0; // 含まれる個数 Scanner sc = new Scanner(System.in); System.out.print("文字列を入力-->"); String str = sc.next(); // 文字列を入力 System.out.print("文字を1文字入力-->"); char ch = (sc.next()).charAt(0); // 1文字を入力 for(int i=0;i<str.length();i++){ if( str.charAt(i)==ch ) cnt++; // 文字が一致した } System.out.println(" " + ch + "の個数は " + cnt + "個です" ); } } |
| <演習4>の解答例 |
| import java.util.Scanner; class Ensyu1104 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int sum = 0; int bin = 1; System.out.print("4桁の2進数を入力-->"); String str = sc.next(); // 文字列を入力 if( str.charAt(3)=='1' ) sum += bin; //4文字目が1なら+(2の0乗) bin *= 2; if( str.charAt(2)=='1' ) sum += bin; //3文字目が1なら+(2の1乗) bin *= 2; if( str.charAt(1)=='1' ) sum += bin; //2文字目が1なら+(2の2乗) bin *= 2; if( str.charAt(0)=='1' ) sum += bin; //1文字目が1なら+(2の3乗) System.out.println(str + "の10進数は " + sum + " です" ); } } |
| <演習5>の解答例 |
| import java.util.Scanner; class Ensyu1105 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int index; String res; System.out.print("ファイル名を入力-->"); String str = sc.next(); // 文字列を入力 index = str.indexOf('.'); // ピリオドの位置を調べる res = str.substring(index + 1); System.out.println(str + "の拡張子は " + res + " です" ); } } |
| <演習6>の解答例 |
| import java.util.Scanner; class Ensyu1106 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int len; // 文字列の長さ while(true){ System.out.print("文字列を入力-->"); String str = sc.next(); // 文字列を入力 if( str.equals("end")==true ) break; len = str.length(); System.out.println(str + "の文字数は " + len ); } } } |