[关闭]
@Sarah 2015-11-05T17:52:28.000000Z 字数 9714 阅读 896

JAVA 数组 String 异常

java笔记
构造函数可以用右键source自动写,还有toString()

string

常用函数

求字符串长度:.length()

求数组长度:

  1. int i[]=new int[100]
  2. i.length

去掉首尾空格: .trim()

" abc d \t\n ".trim()
返回abc d“”

大小写:

toLower()
toUpper()

  1. strung s="4ABC";
  2. s=s.tolower();
  3. //后面一定要把值赋给一个变量 否则会被回收

转换成char:

  1. s="4abc"
  2. char c[];
  3. c=s.getChars();
  4. //c=“4” "a" "b" "c"
  5. c.length //=4
  6. s.length // =4

indexOf()

  1. "abcabc"
  2. indexOf("c") //2
  3. indexOf("ca") //2
  4. indexOf("ac") //-1
  5. indexOf("a") //0
  6. indexOf("ab,2") //3 从第二个开始往后找“ab”
  7. LastIndexOf()
  1. 这个例子没看懂呢= =
  2. int [] i=new int [10];
  3. Point p=new Point();
  4. Point ps[]=new Point[30];//p[0].x=0 ,p[0]= new Point
  5. for(int j=0;j<30;j++)
  6. ps[j]=new Point();
  7. P[0].x=0;

StringBuffer

  1. String args[])
  2. char c='A'; //char不能有两个字母”AB“
  3. String s=new String("ABC");
  4. s="ABC";
  5. String t;
  6. t="DEF"
  7. s=s+"DEF";//此时变成ABCDEF !这里到底能不能加??!!
  8. //不可变字符串
  9. StringBuffer m=new StringBuffer("ABC");

.SubString()

  1. "ABCDEF".SubString(2,4)
  2. //"CD" 4-2=α 从第二个开始数到第四个之前

.CompareTo()

  1. "ABC".CompareTo("AB")
  2. //1
  3. //前面>后面 1
  4. //前面=后面 0
  5. //前面<后面 -1

.concat()

  1. s="ABC".concat("DEF")
  2. ///"ABC"+"DEF"---"ABCDEF"
  3. //A=65 汉字在两万左右

异常

  1. try{
  2. //这里写可能产生的异常 相关 对象
  3. }
  4. catch(对象){
  5. //引用上面try里的对象
  6. }
  7. catch(对象){
  8. //引用上面try里的对象
  9. }

finally:无论如何都会执行

数组例子

  1. Matrix{
  2. int data[][];
  3. Matrix(int rows,int cols){
  4. if(rows>0 &&cols>0)
  5. data=new int[rows][cols];
  6. else
  7. throw new Exception("XXXXX")
  8. }
  9. }
  1. //数组test
  2. i=m.getData(1,1);
  3. t=m.multiply(n)
  1. 数组相乘
  2. Matrix result=new Matrix(rows,n.getCols());
  3. for(i=0;i<rows;i++)
  4. for(j=0;j<n.getCols();j++)
  5. for(k=0;k<cols;k++)
  6. result.setData(i,j,result.getData(i,j)+data[i][k]*n.getData(k,j));
  7. return result;

J2SE:
1语句 数据类型关键字
2面向对象:类 对象 包 三种特性
object ,static , final
抽象类,接口
3数组:string,异常
4I/o,线程,网络,gui,java.swing


两个方向
j2ee w=网站 html css
andriod 应用

第一个大案例

  1. public class Circle {
  2. Point center;
  3. int radius;
  4. public Circle(Point center, int radius) throws Exception {//声明抛出异常
  5. if (center!=null && radius>=0){
  6. this.center = center;
  7. this.radius = radius;
  8. }
  9. else {
  10. Exception e=new MyException();
  11. throw e;//抛出异常
  12. }
  13. }
  14. public static void main(String[] args) {
  15. Point p=null;
  16. Circle c=null;
  17. try {
  18. c=new Circle(p, 5);
  19. } catch (Exception e) {
  20. // TODO Auto-generated catch block
  21. System.out.println(e);
  22. //javax.swing.JOptionPane.showMessageDialog(null,e);
  23. }
  24. }
  25. }
  1. public class MyException extends Exception {
  2. @Override
  3. public String toString() {
  4. return "参数错误!";
  5. }
  6. }
  1. public class Point {
  2. int x,y;
  3. public Point(int x, int y) {
  4. super();
  5. this.x = x;
  6. this.y = y;
  7. }
  8. @Override
  9. public String toString() {
  10. return "Point [x=" + x + ", y=" + y + "]";
  11. }
  12. }

第二个例子

  1. public class Test {
  2. public static void main(String[] args) {
  3. String c="汉字";
  4. byte[] b=c.getBytes();
  5. char[] cc=new char[c.length()];
  6. c.getChars(0,c.length(),cc,0);
  7. int i=(int)(Math.random()*30);
  8. try{
  9. double d=10/i;
  10. System.out.println(d);
  11. for( i=0;i<=cc.length;i++)
  12. System.out.println((int)cc[i]);
  13. }
  14. catch(ArithmeticException ex){
  15. System.out.println(ex);
  16. }
  17. catch(ArrayIndexOutOfBoundsException ex){
  18. System.out.println("--------"+ex);
  19. return;
  20. }
  21. finally{
  22. System.out.println("123456789");
  23. }
  24. System.out.println((char) 25721);
  25. System.out.println("done.");
  26. }
  27. public static void main1(String[] args) {
  28. // TODO Auto-generated method stub
  29. String s;
  30. StringBuffer t=new StringBuffer("");
  31. char c=65;
  32. System.out.println(c);
  33. int i=0;
  34. for(;i<2000;i++){
  35. t.append( (char) ((int)(Math.random()*26+65)) );
  36. }
  37. s=t.toString();
  38. i=0;
  39. System.out.println(s);
  40. while(true){
  41. int pos=s.indexOf("YU",i);
  42. if(pos<0)
  43. break;
  44. System.out.println(pos);
  45. i=pos+1;
  46. }
  47. // s.g
  48. System.out.println(s.lastIndexOf("YU",1700));
  49. }
  50. }

第三个例子(略)

  1. class WordDictionary{
  2. private final int dictionaryLength=157;
  3. private int index=-1;
  4. private String[] words={
  5. "ability","able","aboard","about","above",
  6. "abroad","absence","absent","absolute","absorb",
  7. "abstract","abundant","abuse","academic","academy",
  8. "accelerate","accent","accept","acceptance","access",
  9. "accident","accidental","accommodation","accompany","accomplish",
  10. "accord","accordance","accordingly","account","accountant",
  11. "accumulate","accuracy","accurate","accuse","accustomed",
  12. "ache","achieve","achievement","acid","acknowledge",
  13. "acquaintance","acquire","acquisition","acre","across",
  14. "action","active","activity","actor","actress",
  15. "actual","acute","adapt","addition","additional",
  16. "address","adequate","adjective","adjust","administration",
  17. "admire","admission","admit","adopt","adult",
  18. "advance","advanced","advantage","adventure","adverb",
  19. "advertise","advertisement","advice","advisable","advise",
  20. "advocate","aeroplane","affair","affect","affection",
  21. "afford","afraid","after","afternoon","again",
  22. "agency","agenda","agent","aggressive","agree",
  23. "agreement","agriculture","ahead","aircraft","airline",
  24. "airplane","against","airport","alarm","alcohol",
  25. "alert","alike","alive","all","alliance",
  26. "allocate","allow","allowance","ally","almost",
  27. "alone","along","alongside","aloud","alphabet",
  28. "already","also","alter","alternative","although",
  29. "altitude","altogether","aluminium","aluminum","always",
  30. "amateur","amaze","ambassador","ambition","ambulance",
  31. "amid","among","amongst","amount","amuse",
  32. "analyse","analysis","analyze","ancestor","anchor",
  33. "ancient","and","anger","angle","angry",
  34. "animal","ankle","anniversary","announce","annoy",
  35. "annual","another","answer","anticipate","antique",
  36. "anxiety","anxious"};
  37. public String getMagicWord(){
  38. int i=(int)(Math.random()*dictionaryLength);
  39. index=i;
  40. return convertWord(words[i]);
  41. }
  42. private String convertWord(String word){
  43. char[] charsInWord=word.toCharArray();
  44. for(int i=charsInWord.length-1; i>0; i--)
  45. for(int j=0; j<i; j++)
  46. if ( charsInWord[ j ] > charsInWord[ j+1 ] ){
  47. char temp=charsInWord[ j ];
  48. charsInWord[ j ]=charsInWord[ j+1 ];
  49. charsInWord[ j+1 ]=temp;
  50. }
  51. return new String(charsInWord);
  52. }
  53. public String getOriginalWord(){
  54. return words[index];
  55. }
  56. }
  57. class GuessWord{
  58. public static void main(String args[]){
  59. WordDictionary wd=new WordDictionary();
  60. int guessTimes=0,correctTimes=0;
  61. while(true){
  62. System.out.println("猜猜这是什么单词:"+wd.getMagicWord());
  63. guessTimes++;
  64. if(wd.getOriginalWord().equals(KeyInput.readString())){
  65. System.out.println("对了,就是 "+wd.getOriginalWord());
  66. correctTimes++;
  67. }
  68. else
  69. System.out.println("错了,是 "+wd.getOriginalWord());
  70. System.out.print("继续玩吗?(y/n)");
  71. if(KeyInput.readString().toLowerCase().equals("n"))
  72. break;
  73. }
  74. System.out.println("猜对率为"+(correctTimes*100/guessTimes)+"%,拜拜喽...");
  75. }
  76. }
  1. import java.io.*;
  2. public class KeyInput {
  3. static InputStreamReader isr = new InputStreamReader(System.in);
  4. static BufferedReader br = new BufferedReader(isr);
  5. public static int readInt() {
  6. int i = 0;
  7. try {
  8. i = Integer.parseInt(readString());
  9. } catch (Exception e) {
  10. System.out.println(e);
  11. }
  12. return i;
  13. }
  14. public static float readFloat() {
  15. float f = 0.0f;
  16. try {
  17. f = Float.parseFloat(readString());
  18. } catch (Exception e) {
  19. System.out.println(e);
  20. }
  21. return f;
  22. }
  23. public static double readDouble() {
  24. double d = 0.0;
  25. try {
  26. d = Double.parseDouble(readString());
  27. } catch (Exception e) {
  28. System.out.println(e);
  29. }
  30. return d;
  31. }
  32. public static String readString() {
  33. String s = "";
  34. try {
  35. s = br.readLine();
  36. if (s.length() == 0)
  37. s = br.readLine();
  38. } catch (Exception e) {
  39. System.out.println(e);
  40. }
  41. return s;
  42. }
  43. public static boolean readBoolean() {
  44. if (readString().toUpperCase().equals("TRUE"))
  45. return true;
  46. else
  47. return false;
  48. }
  49. public static char readChar() {
  50. try {
  51. return readString().charAt(0);
  52. } catch (Exception e) {
  53. System.out.println(e);
  54. }
  55. return ' ';
  56. }
  57. public static void main(String args[]) {
  58. System.out.print("Please input an integer number:");
  59. System.out.println("Your input is " + KeyInput.readInt());
  60. System.out.print("Please input a float number:");
  61. System.out.println("Your input is " + KeyInput.readFloat());
  62. System.out.print("Please input a double number:");
  63. System.out.println("Your input is " + KeyInput.readDouble());
  64. System.out.print("Please input a string:");
  65. System.out.println("Your input is " + KeyInput.readString());
  66. System.out.print("Please input a boolean value:");
  67. System.out.println("Your input is " + KeyInput.readBoolean());
  68. System.out.print("Please input a char:");
  69. System.out.println("Your input is " + KeyInput.readChar());
  70. }
  71. }

大作业Matrix

  1. public class IllegalArgumentException extends Exception {
  2. @Override
  3. public String toString() {
  4. return "矩阵行数或列数非法";
  5. }
  6. }

public class IllegalIndexException extends Exception{

@Override
public String toString() {
    return "矩阵行号或列号非法";
}

}

  1. public class Matrix {
  2. int rows;
  3. int cols;
  4. double data[][];
  5. private Matrix() {
  6. }
  7. public Matrix(int rows, int cols) throws IllegalArgumentException {
  8. super();
  9. if (rows >= 1 && cols >= 1) {
  10. this.rows = rows;
  11. this.cols = cols;
  12. this.data = new double[rows][cols];
  13. } else {
  14. //Exception e = new IllegalArgumentException();
  15. throw new IllegalArgumentException();
  16. }
  17. }
  18. public Matrix(int rows, int cols, double[][] data) throws IllegalArgumentException {
  19. super();
  20. if (rows >= 1 && cols >= 1) {
  21. this.rows = rows;
  22. this.cols = cols;
  23. this.data = data;
  24. } else {
  25. //Exception e = new IllegalArgumentException();
  26. throw new IllegalArgumentException();
  27. }
  28. }
  29. public double getData(int rows, int cols) throws IllegalIndexException {
  30. if (this.cols > cols && this.rows > rows) {
  31. return data[rows][cols];
  32. } else {
  33. //Exception f = new IllegalIndexException();
  34. throw new IllegalIndexException();
  35. }
  36. }
  37. public void setData(int rows, int cols, double value) throws IllegalIndexException {
  38. if (this.cols > cols && this.rows > rows) {
  39. this.data[rows][cols] = value;
  40. // return data[rows][cols];
  41. } else {
  42. //Exception f = new IllegalIndexException();
  43. throw new IllegalIndexException();
  44. }
  45. }
  46. public Matrix multiply(Matrix m) throws MatrixMultiplicationException,
  47. IllegalIndexException,IllegalArgumentException{
  48. if (cols == m.rows) {
  49. Matrix result = new Matrix(rows, m.cols);
  50. int i, j, k;
  51. for (i = 0; i < rows; i++)
  52. for (j = 0; j < m.cols; j++)
  53. for (k = 0; k < cols; k++)
  54. result.setData(i, j, result.getData(i, j) + data[i][k]
  55. * m.getData(k, j));
  56. return result;
  57. } else {
  58. // Exception g = new MatrixMultiplicationException();
  59. throw new MatrixMultiplicationException();
  60. }
  61. }
  62. public String toString() {
  63. StringBuffer s = new StringBuffer("");
  64. for (int i = 0; i < rows; i++) {
  65. s.append("[");
  66. for (int j = 0; j < cols; j++) {
  67. s.append(data[i][j]);
  68. if (j + 1 != cols)
  69. s.append("\t");
  70. }
  71. s.append("]\n");
  72. }
  73. return s.toString();
  74. }
  75. }
  1. public class MatrixMultiplicationException extends Exception {
  2. @Override
  3. public String toString() {
  4. return "矩阵无法相乘异常";
  5. }
  6. }
  1. public class MatrixTest {
  2. public static void main(String[] args) {
  3. try {
  4. Matrix m = new Matrix(1, 7);
  5. Matrix n = new Matrix(7, 5);
  6. for (int i = 0; i < m.rows; i++)
  7. for (int j = 0; j < m.cols; j++)
  8. m.setData(i, j, (int) (Math.random() * 10));
  9. for (int i = 0; i < n.rows; i++)
  10. for (int j = 0; j < n.cols; j++)
  11. n.setData(i, j, (int) (Math.random() * 10));
  12. Matrix r = m.multiply(n);
  13. System.out.println(m);
  14. System.out.println(n);
  15. System.out.println(r);
  16. } catch (IllegalArgumentException e) {
  17. System.out.println(e);
  18. } catch (IllegalIndexException f) {
  19. System.out.println(f);
  20. } catch (MatrixMultiplicationException g) {
  21. System.out.println(g);
  22. }
  23. catch(Exception e){
  24. System.out.println(e);
  25. }
  26. }
  27. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注