@Sarah
2015-11-05T17:52:28.000000Z
字数 9714
阅读 966
java笔记
构造函数可以用右键source自动写,还有toString()
常用函数
求数组长度:
int i[]=new int[100]i.length
" abc d \t\n ".trim()
返回abc d“”
toLower()
toUpper()
例
strung s="4ABC";s=s.tolower();//后面一定要把值赋给一个变量 否则会被回收
s="4abc"char c[];c=s.getChars();//c=“4” "a" "b" "c"c.length //=4s.length // =4
"abcabc"indexOf("c") //2indexOf("ca") //2indexOf("ac") //-1indexOf("a") //0indexOf("ab,2") //3 从第二个开始往后找“ab”LastIndexOf()
这个例子没看懂呢= =int [] i=new int [10];Point p=new Point();Point ps[]=new Point[30];//p[0].x=0 ,p[0]= new Pointfor(int j=0;j<30;j++)ps[j]=new Point();P[0].x=0;
(String args[])char c='A'; //char不能有两个字母”AB“String s=new String("ABC");s="ABC";String t;t="DEF"s=s+"DEF";//此时变成ABCDEF !这里到底能不能加??!!//不可变字符串StringBuffer m=new StringBuffer("ABC");
"ABCDEF".SubString(2,4)//"CD" 4-2=α 从第二个开始数到第四个之前
"ABC".CompareTo("AB")//1//前面>后面 1//前面=后面 0//前面<后面 -1
s="ABC".concat("DEF")///"ABC"+"DEF"---"ABCDEF"//A=65 汉字在两万左右
try{//这里写可能产生的异常 相关 对象}catch(对象){//引用上面try里的对象}catch(对象){//引用上面try里的对象}
finally:无论如何都会执行
数组例子
Matrix{int data[][];Matrix(int rows,int cols){if(rows>0 &&cols>0)data=new int[rows][cols];elsethrow new Exception("XXXXX")}}
//数组testi=m.getData(1,1);t=m.multiply(n)
数组相乘Matrix result=new Matrix(rows,n.getCols());for(i=0;i<rows;i++)for(j=0;j<n.getCols();j++)for(k=0;k<cols;k++)result.setData(i,j,result.getData(i,j)+data[i][k]*n.getData(k,j));return result;
J2SE:
1语句 数据类型关键字
2面向对象:类 对象 包 三种特性
object ,static , final
抽象类,接口
3数组:string,异常
4I/o,线程,网络,gui,java.swing
两个方向
j2ee w=网站 html css
andriod 应用
第一个大案例
public class Circle {Point center;int radius;public Circle(Point center, int radius) throws Exception {//声明抛出异常if (center!=null && radius>=0){this.center = center;this.radius = radius;}else {Exception e=new MyException();throw e;//抛出异常}}public static void main(String[] args) {Point p=null;Circle c=null;try {c=new Circle(p, 5);} catch (Exception e) {// TODO Auto-generated catch blockSystem.out.println(e);//javax.swing.JOptionPane.showMessageDialog(null,e);}}}
public class MyException extends Exception {@Overridepublic String toString() {return "参数错误!";}}
public class Point {int x,y;public Point(int x, int y) {super();this.x = x;this.y = y;}@Overridepublic String toString() {return "Point [x=" + x + ", y=" + y + "]";}}
第二个例子
public class Test {public static void main(String[] args) {String c="汉字";byte[] b=c.getBytes();char[] cc=new char[c.length()];c.getChars(0,c.length(),cc,0);int i=(int)(Math.random()*30);try{double d=10/i;System.out.println(d);for( i=0;i<=cc.length;i++)System.out.println((int)cc[i]);}catch(ArithmeticException ex){System.out.println(ex);}catch(ArrayIndexOutOfBoundsException ex){System.out.println("--------"+ex);return;}finally{System.out.println("123456789");}System.out.println((char) 25721);System.out.println("done.");}public static void main1(String[] args) {// TODO Auto-generated method stubString s;StringBuffer t=new StringBuffer("");char c=65;System.out.println(c);int i=0;for(;i<2000;i++){t.append( (char) ((int)(Math.random()*26+65)) );}s=t.toString();i=0;System.out.println(s);while(true){int pos=s.indexOf("YU",i);if(pos<0)break;System.out.println(pos);i=pos+1;}// s.gSystem.out.println(s.lastIndexOf("YU",1700));}}
第三个例子(略)
class WordDictionary{private final int dictionaryLength=157;private int index=-1;private String[] words={"ability","able","aboard","about","above","abroad","absence","absent","absolute","absorb","abstract","abundant","abuse","academic","academy","accelerate","accent","accept","acceptance","access","accident","accidental","accommodation","accompany","accomplish","accord","accordance","accordingly","account","accountant","accumulate","accuracy","accurate","accuse","accustomed","ache","achieve","achievement","acid","acknowledge","acquaintance","acquire","acquisition","acre","across","action","active","activity","actor","actress","actual","acute","adapt","addition","additional","address","adequate","adjective","adjust","administration","admire","admission","admit","adopt","adult","advance","advanced","advantage","adventure","adverb","advertise","advertisement","advice","advisable","advise","advocate","aeroplane","affair","affect","affection","afford","afraid","after","afternoon","again","agency","agenda","agent","aggressive","agree","agreement","agriculture","ahead","aircraft","airline","airplane","against","airport","alarm","alcohol","alert","alike","alive","all","alliance","allocate","allow","allowance","ally","almost","alone","along","alongside","aloud","alphabet","already","also","alter","alternative","although","altitude","altogether","aluminium","aluminum","always","amateur","amaze","ambassador","ambition","ambulance","amid","among","amongst","amount","amuse","analyse","analysis","analyze","ancestor","anchor","ancient","and","anger","angle","angry","animal","ankle","anniversary","announce","annoy","annual","another","answer","anticipate","antique","anxiety","anxious"};public String getMagicWord(){int i=(int)(Math.random()*dictionaryLength);index=i;return convertWord(words[i]);}private String convertWord(String word){char[] charsInWord=word.toCharArray();for(int i=charsInWord.length-1; i>0; i--)for(int j=0; j<i; j++)if ( charsInWord[ j ] > charsInWord[ j+1 ] ){char temp=charsInWord[ j ];charsInWord[ j ]=charsInWord[ j+1 ];charsInWord[ j+1 ]=temp;}return new String(charsInWord);}public String getOriginalWord(){return words[index];}}class GuessWord{public static void main(String args[]){WordDictionary wd=new WordDictionary();int guessTimes=0,correctTimes=0;while(true){System.out.println("猜猜这是什么单词:"+wd.getMagicWord());guessTimes++;if(wd.getOriginalWord().equals(KeyInput.readString())){System.out.println("对了,就是 "+wd.getOriginalWord());correctTimes++;}elseSystem.out.println("错了,是 "+wd.getOriginalWord());System.out.print("继续玩吗?(y/n)");if(KeyInput.readString().toLowerCase().equals("n"))break;}System.out.println("猜对率为"+(correctTimes*100/guessTimes)+"%,拜拜喽...");}}
import java.io.*;public class KeyInput {static InputStreamReader isr = new InputStreamReader(System.in);static BufferedReader br = new BufferedReader(isr);public static int readInt() {int i = 0;try {i = Integer.parseInt(readString());} catch (Exception e) {System.out.println(e);}return i;}public static float readFloat() {float f = 0.0f;try {f = Float.parseFloat(readString());} catch (Exception e) {System.out.println(e);}return f;}public static double readDouble() {double d = 0.0;try {d = Double.parseDouble(readString());} catch (Exception e) {System.out.println(e);}return d;}public static String readString() {String s = "";try {s = br.readLine();if (s.length() == 0)s = br.readLine();} catch (Exception e) {System.out.println(e);}return s;}public static boolean readBoolean() {if (readString().toUpperCase().equals("TRUE"))return true;elsereturn false;}public static char readChar() {try {return readString().charAt(0);} catch (Exception e) {System.out.println(e);}return ' ';}public static void main(String args[]) {System.out.print("Please input an integer number:");System.out.println("Your input is " + KeyInput.readInt());System.out.print("Please input a float number:");System.out.println("Your input is " + KeyInput.readFloat());System.out.print("Please input a double number:");System.out.println("Your input is " + KeyInput.readDouble());System.out.print("Please input a string:");System.out.println("Your input is " + KeyInput.readString());System.out.print("Please input a boolean value:");System.out.println("Your input is " + KeyInput.readBoolean());System.out.print("Please input a char:");System.out.println("Your input is " + KeyInput.readChar());}}
大作业Matrix
public class IllegalArgumentException extends Exception {@Overridepublic String toString() {return "矩阵行数或列数非法";}}
public class IllegalIndexException extends Exception{
@Override
public String toString() {
return "矩阵行号或列号非法";
}
}
public class Matrix {int rows;int cols;double data[][];private Matrix() {}public Matrix(int rows, int cols) throws IllegalArgumentException {super();if (rows >= 1 && cols >= 1) {this.rows = rows;this.cols = cols;this.data = new double[rows][cols];} else {//Exception e = new IllegalArgumentException();throw new IllegalArgumentException();}}public Matrix(int rows, int cols, double[][] data) throws IllegalArgumentException {super();if (rows >= 1 && cols >= 1) {this.rows = rows;this.cols = cols;this.data = data;} else {//Exception e = new IllegalArgumentException();throw new IllegalArgumentException();}}public double getData(int rows, int cols) throws IllegalIndexException {if (this.cols > cols && this.rows > rows) {return data[rows][cols];} else {//Exception f = new IllegalIndexException();throw new IllegalIndexException();}}public void setData(int rows, int cols, double value) throws IllegalIndexException {if (this.cols > cols && this.rows > rows) {this.data[rows][cols] = value;// return data[rows][cols];} else {//Exception f = new IllegalIndexException();throw new IllegalIndexException();}}public Matrix multiply(Matrix m) throws MatrixMultiplicationException,IllegalIndexException,IllegalArgumentException{if (cols == m.rows) {Matrix result = new Matrix(rows, m.cols);int i, j, k;for (i = 0; i < rows; i++)for (j = 0; j < m.cols; j++)for (k = 0; k < cols; k++)result.setData(i, j, result.getData(i, j) + data[i][k]* m.getData(k, j));return result;} else {// Exception g = new MatrixMultiplicationException();throw new MatrixMultiplicationException();}}public String toString() {StringBuffer s = new StringBuffer("");for (int i = 0; i < rows; i++) {s.append("[");for (int j = 0; j < cols; j++) {s.append(data[i][j]);if (j + 1 != cols)s.append("\t");}s.append("]\n");}return s.toString();}}
public class MatrixMultiplicationException extends Exception {@Overridepublic String toString() {return "矩阵无法相乘异常";}}
public class MatrixTest {public static void main(String[] args) {try {Matrix m = new Matrix(1, 7);Matrix n = new Matrix(7, 5);for (int i = 0; i < m.rows; i++)for (int j = 0; j < m.cols; j++)m.setData(i, j, (int) (Math.random() * 10));for (int i = 0; i < n.rows; i++)for (int j = 0; j < n.cols; j++)n.setData(i, j, (int) (Math.random() * 10));Matrix r = m.multiply(n);System.out.println(m);System.out.println(n);System.out.println(r);} catch (IllegalArgumentException e) {System.out.println(e);} catch (IllegalIndexException f) {System.out.println(f);} catch (MatrixMultiplicationException g) {System.out.println(g);}catch(Exception e){System.out.println(e);}}}