精华内容
下载资源
问答
  • java 编程思想 第五版 word
  • java编程思想中文word版可供大家学习访问
  • Java编程思想文字版

    2012-02-19 19:46:41
    Java编程思想,高清文字版 并非扫描的,可以直接打印出来,也可以用其他软件转换成word只打印其中的一部分章节
  • public static Pattern WORD_PATTERN = Pattern.compile("^java", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); public static void main(String[] args) { Matcher m = WORD_PATTERN....
  • Java编程思想(十五) —— 类型信息之反射

    讲完.class,Class之后,继续。


    1)泛化的Class引用

    Class也可以加入泛型,加入之后会进行类型检查。


    贴一下书上原话,Class<?>优于Class,虽然他们是等价的,Class<?>的好处是碰巧或疏忽使用了一个非具体的类引用。我搞不懂这个所谓非具体是什么?

    后面弄懂了,其实<?>作为通配符,就是未知的,直接写结论的话不能写个具体类型吧,作者的意思其实就是说加了泛型的Class就是选择了非具体的版本。


    加入泛型的原因是提供编译期间的类型检查,操作失误的话便会显示错误,但是使用普通的Class的时候,就要到等到运行的时候。


    还有这个Class<T>,JDK文档中:

    T - the type of the class modeled by thisClass object. For example, the type ofString.class isClass<String>. UseClass<?> if the class being modeled is unknown.
    <T>是使用泛型类的声明。包括:

    Interface List<E>

    • Type Parameters:
      E - the type of elements in this list

    一样也是声明。


    2)转型语法

    SE5添加的用于Class引用转型的语法。

    class Gun{
        int price = 1;
    }
    class DeathGun extends Gun{
        int price = 2;
    }
    public class TestCast {
        public static void main(String[] args) {
            Gun g = new DeathGun();
            Class<DeathGun> d = DeathGun.class;
            //泛型的用处 类型不匹配 
            //Class<DeathGun> dd = Gun.class;  
            DeathGun gg = d.cast(g);
            System.out.println(gg.price);
        }
    }
    
    cast源码:
    public T cast(Object obj) {
        if (obj != null && !isInstance(obj))
           throw new ClassCastException(cannotCastMsg(obj));
        return (T) obj;
    }

    3)类型转换前的检查

    if(x instanceof TV){
      ((TV)x).show();
    }

    检查对象类型,向下转型时如果有错,则抛出ClassCastException,所以要先使用instanceOf。


    instaceOf与Class的等价性。

    class Father{}
    class Son extends Father{}
    public class Test {
        static void  test(Object o ){
            System.out.println("type: "+o.getClass());
            System.out.println("o instanceof Father: "+(o instanceof Father));
            System.out.println("o instanceof Son: "+(o instanceof Son));
            System.out.println("Father.isInstanceOf(o)"+Father.class.isInstance(o));
            System.out.println("Son.isInstanceOf(o)"+Son.class.isInstance(o));
            System.out.println("o.getClass()==Father.class:"+(o.getClass()==Father.class));
            System.out.println("o.getClass()==Son.class:"+(o.getClass()==Son.class));
            System.out.println("o.getClass().equals(Father.class):"+(o.getClass().equals(Father.class)));
            System.out.println("o.getClass().equals(Son.class):"+(o.getClass().equals(Son.class)));
        }
        
        public static void main(String[] args) {
            test(new Father());
            test(new Son());
        }
    }
    
    result:
    type: class son.Father
    o instanceof Father: true
    o instanceof Son: false
    Father.isInstanceOf(o)true
    Son.isInstanceOf(o)false
    o.getClass()==Father.class:true
    o.getClass()==Son.class:false
    o.getClass().equals(Father.class):true
    o.getClass().equals(Son.class):false
    
    type: class son.Son
    o instanceof Father: true
    o instanceof Son: true
    Father.isInstanceOf(o)true
    Son.isInstanceOf(o)true
    o.getClass()==Father.class:false
    o.getClass()==Son.class:true
    o.getClass().equals(Father.class):false
    o.getClass().equals(Son.class):true
    

    instanceof指的是你是这个类吗?你是这个类的派生类吗?


    4)反射

    书上讲得好简单,3页左右。

    RTTI,运行时类型信息可以告诉你对象的具体类型,但是,这个类型必须在编译时必须已知,这样RTTI才能识别。即在编译时,编译器必须知道要通过RTTI来处理的类。

    这个看起来不是限制,但是置身于大规模的编程中,可能编译时程序无法获知这个对象所属的类。

    RTTI和反射真正的区别只有:RTTI,编译器在编译时检查和打开.class文件,对于反射,.class文件编译时不可获取,是在运行时打开和检查.class文件。


    直接用书上的例子,贴个代码:

    public class ShowMethods {
      private static String usage =
        "usage:\n" +
        "ShowMethods qualified.class.name\n" +
        "To show all methods in class or:\n" +
        "ShowMethods qualified.class.name word\n" +
        "To search for methods involving 'word'";
      private static Pattern p = Pattern.compile("\\w+\\.");
      public static void main(String[] args) {
        if(args.length < 1) {
          System.out.println(usage);
          System.exit(0);
        }
        int lines = 0;
        try {
          Class<?> c = Class.forName(args[0]);
          Method[] methods = c.getMethods();
          Constructor[] ctors = c.getConstructors();
          if(args.length == 1) {
            for(Method method : methods)
              System.out.println(
                p.matcher(method.toString()).replaceAll(""));
            for(Constructor ctor : ctors)
              System.out.println(p.matcher(ctor.toString()).replaceAll(""));
            lines = methods.length + ctors.length;
          } else {
    //其实作者这样写是,method匹配会匹配,如果我java ShowMethods ShowMethods ShowMethods
    //本来的话是提取其中的一个,但是args[1]为ShowMethods,刚刚好匹配到的就是ShowMethods本身自带的方法,也就是main方法。
             for(Method method : methods)
              if(method.toString().indexOf(args[1]) != -1) {
                System.out.println(
                  p.matcher(method.toString()).replaceAll(""));
                lines++;
              }
            for(Constructor ctor : ctors)
              if(ctor.toString().indexOf(args[1]) != -1) {
                System.out.println(p.matcher(
                  ctor.toString()).replaceAll(""));
                lines++;
              }
          }
        } catch(ClassNotFoundException e) {
          System.out.println("No such class: " + e);
        }
      }
    } 
    
    
    F:\>java ShowMethods ShowMethods
    public static void main(String[])
    public final native Class getClass()
    public native int hashCode()
    public boolean equals(Object)
    public String toString()
    public final native void notify()
    public final native void notifyAll()
    public final native void wait(long) throws InterruptedException
    public final void wait(long,int) throws InterruptedException
    public final void wait() throws InterruptedException
    public ShowMethods()
    
    

    慢慢看Matcher的replaceAll方法,不同于String的replaceAll,后者有两个参数,一个替换内容,一个是要被替换的内容。而前者只有一个参数。

    public String replaceAll(String replacement)
    Replaces every subsequence of the input sequence that matches the pattern with the given replacement string.
    public class TestString {  
        public static void main(String[] args) {  
            String s = "0898((*(*))(";
            //正则表达式编译进Pattern
            Pattern p = Pattern.compile("\\W");
            //p.matcher返回的是Matcher对象,Matcher的replaceAll方法是可以将匹配的字符串
            //替换成方法参数中的内容。
            System.out.println(p.matcher(s).replaceAll("-"));
        }  
    }  
    result:0898--------
    
    如果没有正则表达式的替换,那么结果是:

    public static void ShowMethods.main(java.lang.String[])
    public final native java.lang.Class java.lang.Object.getClass()
    public native int java.lang.Object.hashCode()
    public boolean java.lang.Object.equals(java.lang.Object)
    public java.lang.String java.lang.Object.toString()
    public final native void java.lang.Object.notify()
    public final native void java.lang.Object.notifyAll()
    public final native void java.lang.Object.wait(long) throws java.lang.Interrupte
    dException
    public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedEx
    ception
    public final void java.lang.Object.wait() throws java.lang.InterruptedException
    public ShowMethods()
    其实就是替换掉类前面的包名。

    有没有发现,forName的结果在编译时不可知,我们是在运行的时候传进Class参数的。虽然刚开始的时候没用到这么高级的东西,但是后面学得深入了之后就发现有些东西在使用,如Spring。


    getMethods拿到的是类的所有共有方法,包括自身,从父类继承,从接口实现的public方法。

    还有一个是getDeclaredMethods拿到的是类自身声明的方法,不止是public方法,protected也能拿到,甚至是private。(刚开始我也是很疑惑,不是经常强调封装,私有不让人家看到吗,怎么可以直接拿到private的东西的,其实可以这样看,什么东西有个度,但是这个度并不是一尘不破,有一定的后门)。


    getConstructors返回的是public的构造器。试了一下,私有的构造器不会显示。书上讲到这里就停了,继续扩展:

    以前看过Java反射教程里面介绍的很好。


    一、未知的方法调用

    public class TestRefl {
        public static void main(String[] args) {
            UnKnown uk = new UnKnown();
            Method m = null;
            try {
                m = uk.getClass().getMethod("print", new Class<?>[0]);
                    m.invoke(uk);
            } catch (NoSuchMethodException | InvocationTargetException| SecurityException  |IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
    
    class UnKnown{
        public void print(){
            System.out.println("haha");
        }
    }
    之前我特地将方法改成private,发现是找不到方法的,只有改为public。


    二、对象的创建

    public class TestRefl {
        public static void main(String[] args) {
           Class c = null;
           try {
            c = c.forName("son.UnKnown");
            System.out.println(c.getName());
        } catch (ClassNotFoundException e) {
            System.out.println("not found");
        }
           try {
            UnKnown u = (UnKnown) c.newInstance();
            u.print();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        }
    }
    
    class UnKnown{
       static  void print(){
            System.out.println("haha");
        }
    }

    通过构造函数获取对象。

    public class TestRefl {
        public static void main(String[] args) {
            Class c = null;
            try {
                c = c.forName("son.UnKnown");
            } catch (ClassNotFoundException e) {
                System.out.println("not found");
            }
            Constructor<?> ct[] = c.getConstructors();
            try {
                UnKnown u = (UnKnown) ct[0].newInstance();
                UnKnown u2 = (UnKnown) ct[1].newInstance(1);
                u.print();
                u2.print();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
    class UnKnown {
        public UnKnown() {
        }
    
        public UnKnown(int i) {
        }
    
        static void print() {
            System.out.println("haha");
        }
    }
    构造函数数组有顺序,0是无参的那个构造函数,1为传参,在方法中直接传参即可。当然私有的构造方法是拿不到的。


    解释到RTTI和反射的不同的时候,反过来可以说明反射的作用,就是运行时检查对象的类型,任意调用对象的方法(Spring和servlet中都用到了,注意到没有,我们在xml配置,然后属性会根据xml注入),同时可以知道方法参数和属性。


    反射还是很强大,接下来会介绍动态代理,以前被虐过的一个设计模式。

    展开全文
  • Java编程思想(十三) —— 字符串(2)

    上篇讲到String的基本用法及StringBuilder和String的比较。继续。


    给大家感受一下RednaxelaFX的厉害,他大学看的书。

    嗯,这就是去硅谷的水平,所以,还是继续看书吧。


    1)格式化输出

    确实,说到C的printf,是不能用重载的+操作符的。

    printf("%d %f", x , y);
    %d这些为格式修饰符,%d表示整数,x插入到%d的位置,%f表示浮点数,y查到%f的位置

    Java也模仿了C:

    public class TestString {
        public static void main(String[] args) {
            int x = 1;
            float y = 1.223f;
            System.out.printf("%d %f",x,y);
            System.out.println();
            System.out.format("%d %f",x,y);
        }
    }


    可以用Formatter在控制台完美的控制间隔,不用你自己去数几个空格了。

    public class TestString {
        public static void main(String[] args) {
            Formatter fm = new Formatter(System.out);
            fm.format("%-5s %5s %10s ", "Name","Age","School");
        }
    }
    %数字+s这样的表达像c,位置可以移动。


     System.out.println(String.format("%h", 17));
     fm.format("%h", 17);
    
    16进制的格式化输出。


    2)正则表达式(regex :regular expression)

    字符串处理,文件批处理中经常使用到,很好用,也是容易忘。这个点结合网上的一些知识点来写。

    -? 一个可能带有负号的数字不包括数字。

    \d   表示一位数字,注意其他语言的\\是在正则表达式中是一个反斜杠,而在java中是正要插入正则表达式的\。


    举一反三,那么\d在java中就是\\d了,真正想插入一条反斜杠就要\\\。

    String的匹配 利用String的match方法
    
    public class TestString {
        public static void main(String[] args) {
            System.out.println("-3444".matches("-?\\d+"));
            System.out.println("-3".matches("-?\\d"));
            System.out.println("-3".matches("(-|\\+)?\\d"));
        }
    }
    
    result:都是ture
    

    (-|\\+)? 这个比较复杂,|是或的意思,\\+,由于加号有特殊含义,那么要\\转义,所以就是有加号或者负号的其中一个,或者都没有。


    split方法:

    经常使用的时候是根据空格切割。

    String s = Arrays.toString("sdfsdf sf sdf".split(" "));
    其实还可以在split参数中输入正则表达式进行切割:

    String s = Arrays.toString("sdfsdf sf sdf".split("\\W+"));
    String s2 = Arrays.toString("sdfsdf sf sdf".split("n\\W+"));
    \w是非单词字符,\w为单词字符,n\\W+ 字母n后跟着一个或多个非中文字符。


    参考:

    http://blog.csdn.net/kdnuggets/article/details/2526588

    和JDK的Pattern类:


    ConstructMatches
     
    Characters
    xThe character x
    \\The backslash character
    \0nThe character with octal value 0n (0 <= n <= 7)
    \0nnThe character with octal value 0nn (0 <= n <= 7)
    \0mnnThe character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7)
    \xhhThe character with hexadecimal value 0xhh
    \uhhhhThe character with hexadecimal value 0xhhhh
    \x{h...h}The character with hexadecimal value 0xh...h (Character.MIN_CODE_POINT  <= 0xh...h <= Character.MAX_CODE_POINT)
    \tThe tab character ('\u0009')
    \nThe newline (line feed) character ('\u000A')
    \rThe carriage-return character ('\u000D')
    \fThe form-feed character ('\u000C')
    \aThe alert (bell) character ('\u0007')
    \eThe escape character ('\u001B')
    \cxThe control character corresponding to x
     
    Character classes
    [abc]
    a, b, or c (simple class)
    [^abc]Any character except a, b, or c (negation)
    [a-zA-Z]a through z or A through Z, inclusive (range)
    [a-d[m-p]]a through d, or m through p:[a-dm-p] (union)
    [a-z&&[def]]d, e, or f (intersection)
    [a-z&&[^bc]]a through z, except for b and c: [ad-z] (subtraction)
    [a-z&&[^m-p]]a through z, and not m through p: [a-lq-z](subtraction)
     
    Predefined character classes
    .Any character (may or may not match line terminators)
    \dA digit: [0-9]
    \DA non-digit: [^0-9]
    \sA whitespace character: [ \t\n\x0B\f\r]
    \SA non-whitespace character: [^\s]
    \wA word character: [a-zA-Z_0-9]
    \WA non-word character: [^\w]
     
    POSIX character classes (US-ASCII only)
    \p{Lower}A lower-case alphabetic character: [a-z]
    \p{Upper}An upper-case alphabetic character:[A-Z]
    \p{ASCII}All ASCII:[\x00-\x7F]
    \p{Alpha}An alphabetic character:[\p{Lower}\p{Upper}]
    \p{Digit}A decimal digit: [0-9]
    \p{Alnum}An alphanumeric character:[\p{Alpha}\p{Digit}]
    \p{Punct}Punctuation: One of !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
    \p{Graph}A visible character: [\p{Alnum}\p{Punct}]
    \p{Print}A printable character: [\p{Graph}\x20]
    \p{Blank}A space or a tab: [ \t]
    \p{Cntrl}A control character: [\x00-\x1F\x7F]
    \p{XDigit}A hexadecimal digit: [0-9a-fA-F]
    \p{Space}A whitespace character: [ \t\n\x0B\f\r]
     
    java.lang.Character classes (simple java character type)
    \p{javaLowerCase}Equivalent to java.lang.Character.isLowerCase()
    \p{javaUpperCase}Equivalent to java.lang.Character.isUpperCase()
    \p{javaWhitespace}Equivalent to java.lang.Character.isWhitespace()
    \p{javaMirrored}Equivalent to java.lang.Character.isMirrored()
     
    Classes for Unicode scripts, blocks, categories and binary properties
    \p{IsLatin}A Latin script character (script)
    \p{InGreek}A character in the Greek block (block)
    \p{Lu}An uppercase letter (category)
    \p{IsAlphabetic}An alphabetic character (binary property)
    \p{Sc}A currency symbol
    \P{InGreek}Any character except one in the Greek block (negation)
    [\p{L}&&[^\p{Lu}]] Any letter except an uppercase letter (subtraction)
     
    Boundary matchers
    ^The beginning of a line
    $The end of a line
    \bA word boundary
    \BA non-word boundary
    \AThe beginning of the input
    \GThe end of the previous match
    \ZThe end of the input but for the final terminator, if any
    \zThe end of the input


    量词:吸收文本的方式

    Greedy quantifiers            贪婪型
    X?X, once or not at all
    X*X, zero or more times
    X+X, one or more times
    X{n}X, exactly n times
    X{n,}X, at least n times
    X{n,m}X, at least n but not more than m times
     
    Reluctant quantifiers
    X??X, once or not at all
    X*?X, zero or more times
    X+?X, one or more times
    X{n}?X, exactly n times
    X{n,}?X, at least n times
    X{n,m}?X, at least n but not more than m times
     
    Possessive quantifiers
    X?+X, once or not at all
    X*+X, zero or more times
    X++X, one or more times
    X{n}+X, exactly n times
    X{n,}+X, at least n times
    X{n,m}+X, at least n but not more than m times
     
    Logical operators
    XYX followed by Y
    X|YEither X or Y
    (X)X, as a capturing group
     
    Back references
    \nWhatever the nth capturing group matched
    \k<name>Whatever the named-capturing group "name" matched
     
    Quotation
    \Nothing, but quotes the following character
    \QNothing, but quotes all characters until \E
    \ENothing, but ends quoting started by \Q
     
    Special constructs (named-capturing and non-capturing)
    (?<name>X)X, as a named-capturing group
    (?:X)X, as a non-capturing group
    (?idmsuxU-idmsuxU) Nothing, but turns match flags i d m s u x U on - off
    (?idmsux-idmsux:X)  X, as a non-capturing group with the given flagsidmsu x on - off
    (?=X)X, via zero-width positive lookahead
    (?!X)X, via zero-width negative lookahead
    (?<=X)X, via zero-width positive lookbehind
    (?<!X)X, via zero-width negative lookbehind
    (?>X)X, as an independent, non-capturing group


    3)Pattern和Matcher

    public class TestString {
        public static void main(String[] args) {
            Pattern p = Pattern.compile("\\W+");
            Matcher m = p.matcher("qw");
            System.out.println(m.matches());
        }
    }
    Pattern.compile,静态方法,Compiles the given regular expression into a pattern。将一个正则表达式编译进Pattern中。

    p.mathcer,Creates a matcher that will match the given input against this pattern。创建一个matcher将输入和Pattern匹配。



    m.matches,Attempts to match the entire region against the pattern。
    boolean,返回匹配结果。

    这样就可以传入正则表达式,然后对字符串进行匹配。

    1、find和group
    public class TestString {
        public static void main(String[] args) {
            String s = "You're kidding me!";
            Pattern p = Pattern.compile("\\w+");
            Matcher m = p.matcher(s);
            while(m.find()){
                System.out.printf(m.group()+" ");
            }
    
            int i = 0;
            while(m.find(i)){
                System.out.printf(m.group()+" ");
                i++;
            }
        }
    }
    
    result: You re kidding me 
    You ou u re re e kidding kidding idding dding ding ing ng g me me e 
    
    
    
    find可以遍历字符串,寻找正则表达式的匹配,group是 Returns the input subsequence matched by the previous match。这样返回的便是第一个匹配多个单词字符 ,所以便是You。find传入参数后,可以调整开始搜索的位置,刚开始为0,那么匹配的是You,i+1之后,匹配到的是ou。

    2、end和start
    while(m.find()){
                System.out.printf(m.group()+" Start:"+m.start()+" End:"+m.end());
    }
    
    You Start:0 End:3re Start:4 End:6kidding Start:7 End:14me Start:15 End:17
    
    匹配起始位置的索引,匹配结束位置的索引。

    3、split
    其实书上讲属性的东西是最简单的,因为文档有,这种文档有的就是自己动手查动手敲代码。Pattern还有两个

    String[]split(CharSequence input)
    Splits the given input sequence around matches of this pattern.
    String[]split(CharSequence input, int limit)
    Splits the given input sequence around matches of this pattern.
    String string = "kjj~~lkjl~~lkjlJ~~lkj~~";
    System.out.println(Arrays.toString(Pattern.compile("~~").split(string)));
    System.out.println(Arrays.toString(Pattern.compile("~~").split(string,2)));
    
    result:
    [kjj, lkjl, lkjlJ, lkj]
    [kjj, lkjl~~lkjlJ~~lkj~~]
    
    (哈哈,作者竟然在书中直接讽刺Sun里面的java设计者,把Pattern的标记设计得难懂。)

    4)替换操作

    StringreplaceAll(String regex,String replacement)
    Replaces each substring of this string that matches the given regular expression with the given replacement.
    StringreplaceFirst(String regex,String replacement)
    Replaces the first substring of this string that matches the given regular expression with the given replacement.
    replaceFirst替换的是第一个匹配的内容。replaceAll是全部替换。

    接下来还有比这两者好用的处理方法,加入你要找出abcd字母并且替换成大写字母,如果用上面两种写法的话就要处理多次。

    String string = "asdfb  sdfoiwer  sdfcdf wer sd d sdf  cxvxzcv s ef bob b   b ";
    StringBuffer s2 = new StringBuffer();
    Pattern pa = Pattern.compile("[abcd]");
    Matcher mc = pa.matcher(string);
    System.out.println();
    while(mc.find()){
        mc.appendReplacement(s2,mc.group().toUpperCase());
    }
    mc.appendTail(s2);
    System.out.println(s2);
    
    result:AsDfB  sDfoiwer  sDfCDf wer sD D sDf  CxvxzCv s ef BoB B   B 
    
    
    
    mc.find();
    mc.appendReplacement(s2,mc.group().toUpperCase());
    mc.appendTail(s2);
    System.out.println(s2);
    
    result :Asdfb  sdfoiwer  sdfcdf wer sd d sdf  cxvxzcv s ef bob b   b 
    
    替换时也能操作字符串,while的时候能够全部替换,如果不用while,只进行一次find操作,那么s2打印出来的只有A,要达到replaceFirst的效果,要用appendTail方法,加尾巴,就是把剩余没替换的补上。这样才会打印完整。

    reset方法:
    Matcher mc = pa.matcher(string);
    每次mc只能match一个字符串,可以用reset方法重新match其他字符串:
    mc.reset(String newString);

    5)扫描输入
    c的输入很简单,有时java经常写Syso(Eclipse的System.out.println的快捷输入,很早之前一位前辈告诉我的,一直受用)。一直输出,却忘了输入怎么写。
    可读流对象:

    public class TestScanner {
        public static void main(String[] args) {
            BufferedReader br = new BufferedReader(new StringReader("sdfsdf\nsdfsdf\nsdfsdf"));
            try {
                System.out.println(br.readLine());
                System.out.println(br.readLine());
                System.out.println(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    用Scanner也可以。
    Scanner s = new Scanner(System.in);
    System.out.println(s.nextLine());
    可以在控制台输入后输出。

    Scanner定界符:
    public class TestScanner {
        public static void main(String[] args) {
            Scanner s = new Scanner("12, 323, 34, 34, 5");
            s.useDelimiter("\\s*,\\s*");
            while (s.hasNextInt()) {
                System.out.println(s.nextInt());
            }
        }
    }
    昨天看到这里的时候卡住了,本来Scanner根据空白字符对输入进行分词:
    Scanner s = new Scanner("12  323 34 34 5");
    while (s.hasNextInt()) {
        System.out.println(s.nextInt());
    }
    这样可以打印每一个数字。
    昨天想了好久的就是定界符这个东西,为什么我用\\d+,\\d+不行,今天再来看想通了,其实定界是作为分隔符来看,\\s是空格,而*是零次或多次,这样说就是以逗号前后无空白或者一个或多个空白,将Scanner里面的内容分隔开。
    \\d+,\\d+,以逗号前后有数字作为分隔符,肯定不匹配。为了验证,把s改为W一试,也是可以的。

    以前没有Scanner和正则表达式的时候,Java使用的是StringTokenizer,现在基本废弃不用了,当然,IDE还没有提示Deprecated.

    String内容就到这里了,输入输出,格式化输出,正则表达式,用好的话,在批处理方面甚是强大,有空补充一下String不变性和内存分配的内容。


    展开全文
  • 学习Java编程思想

    2005-06-02 17:59:00
    终于有时间把大名鼎鼎的《Java编程思想》通读了一遍,确实是一本好书。通过这次学习把Java系统的学习了一遍,以前会的都是工作中用到的那些,不全面。一直到参加了CA的招聘考试才知道自己的不足。自己总结了一个学习...

    终于有时间把大名鼎鼎的《Java编程思想》通读了一遍,确实是一本好书。

    通过这次学习把Java系统的学习了一遍,以前会的都是工作中用到的那些,不全面。一直到参加了CA的招聘考试才知道自己的不足。

    自己总结了一个学习笔记,由于是word文档不方便直接贴出来。

    下一步想把Java编程中涉及RMI和XML的部分再学一下,这毕竟是参加CA考试时发现的弱点。

    现在由于对工作、经验和职业发展的思考,开始觉得很惶恐,不想再继续做程序员了,但是又不知道路在哪里?机会在哪里?

    展开全文
  • java 编程思想 学习笔记

    Java=++--(C plus plus minus minus),suggesting that Java is C++ with the unnecessary hard parts removed ,and therefore a much simpler language . You will see that many parts are simpler ,and yet in other ways Java isn’t much easier than C++

     

    Operators

    You can’t use a non-boolean as if it were a logical expression as you can in C and C++.

    eg:     int a =1;

           int b=2;

           System.out.println("a || b is "+(a||b));

     

    Be aware, however ,that the comparison of floating point numbers is very strict. A number that is the tiniest fraction different from another number is still “not equal.“ A number that is the tiniest bit above zero is still nonzero.

     

    If you are used to thinking in terms of e as the base of natural logarithms, you must do a mental translation when you see an expression such as 1.39 e-43f in java;it means 1.39*10-43

     

    If you shift a char, byte ,or short ,it will be promoted to int before the shift takes place, and the result will be an int . Only the five low-order bits of the right-hand side will be used .This prevents you from shifting more than the number of bits in an int. If you’re operating on a long ,you’ll get a long result .Only the six low-order bits of the right-hand side will be used ,so you can’t shift more than the number of bits in a long.

     

    Shifts can be combined with the equal sign(<<= or >>= or >>>=)

     

    Although goto is a reserved word in Java ,it is not used in the language; Java has no goto. However, it does have something that looks a bit like a jump tied in with the break and continue keywords .It’s not a jump but rather a way to break out of an iteration statement. The reason it’s often thrown in with discussions of goto is because it uses the same mechanism: a label.

    It’s important to remember that the only reason to use labels in Java is when you have nested loops and you want to break or continue through more than one nested level.

     

    Initialization & Cleanup

    While you can call one constructor using this, you cannot call two. In addition, the constructor call must be the first thing you do, or you’ll get a compiler error message.

     

    The compiler won’t let you call a constructor from inside and method other than a constructor.

     

    Neither garbage collection nor finalization is guaranteed. If the JVM isn’t close to running out of memory, then it might not waste time recovering memory through garbage collection.

     

    public class StaticInitialization {

     

        public static void main(String[] args) {

           System.out.println("Creating new Cupboard() in main");

           new Cupboard();

           System.out.println("Ctreating new Cupboard() in main");

           new Cupboard();

           table.f2(1);

           cupboard.f3(1);

        }

       

        static Table table=new Table();

        static Cupboard cupboard=new Cupboard();

    }

     

    class Bowl{

       

        Bowl(int marker){

           System.out.println("Bowl("+ marker+")");

        }

        void f1(int marker){

            System.out.println("f1("+marker+")");

        }

    }

     

    class Table{

        static Bowl bowl1=new Bowl(1);

        Table(){

           System.out.println("Table()");

           bowl2.f1(1);

        }

        void f2(int marker){

           System.out.println("f2("+marker+")");

        }

        static Bowl bowl2=new Bowl(2);

    }

     

    class Cupboard{

        Bowl bowl3=new Bowl(3);

        static Bowl bowl4=new Bowl(4);

        Cupboard(){

           System.out.println("Cupboard()");

           bowl4.f1(2);

        }

        void f3(int marker){

           System.out.println("f3("+marker+")");

        }

        static Bowl bowl5=new Bowl(5);

    }

     

    output:

    Bowl(1)

    Bowl(2)

    Table()

    f1(1)

    Bowl(4)

    Bowl(5)

    Bowl(3)

    Cupboard()

    f1(2)

    Creating new Cupboard() in main

    Bowl(3)

    Cupboard()

    f1(2)

    Ctreating new Cupboard() in main

    Bowl(3)

    Cupboard()

    f1(2)

    f2(1)

    f3(1)

     

    From the output ,you can see that the static initialization occurs only if it’s necessary. If you don’t create a Table object and you never refer to Table.bowl1 or Table.bowl2,the static Bowl bowl1 and bowl2 will never be created. They are initialized only when the first Table object is created(or the first Static access occurs).After that, the static objects are not reinitialized.

                                                   

    展开全文
  • Java编程思想重点笔记(Java开发必看)

    万次阅读 多人点赞 2014-12-09 13:22:49
    Java学习必读经典,不管是初学者还是大牛都值得一读,这里总结书中的重点知识,这些知识不仅经常出现在各大知名公司的笔试面试过程中,而且在大型项目开发中也是常用的知识,既有简单的概念理解题(比如is-a关系和...
  • Java编程思想:引言

    2007-09-24 14:05:00
    引言同人类任何语言一样,Java为我们提供了一种表达思想的方式。如操作得当,同其他方式相比,随着问题变得愈大和愈复杂,这种表达方式的方便性和灵活性会显露无遗。不可将Java简单想象成一系列特性的集合;如孤立地...
  • Java编程思想(第4版本)1-15章笔记

    千次阅读 多人点赞 2020-11-02 11:17:51
    **注:**大学本科在读学生,趁着课余时间想多了解些Java知识,很多人推荐我读一读《Java编程思想》这本书,网上的口碑也非常不错,于是就买来看看。这本书读起来比较生涩,不适合初学Java的小白读,毕竟是元老级别的...
  • Java编程思想第四版13章 个人练习

    千次阅读 2015-03-26 17:07:49
    练习12:(5)修改groups.java,找出所有不以大写字母开头的单词,不重复的计算其个数。   package thinkjava13; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import ...
  • Java编程思想第四版第十四章习题

    千次阅读 2019-08-08 21:59:14
    1In ToyTest.java, comment out Toy's default constructor andexplain what happens. package job; import java.util.*; interface HasBatteries {} interface Waterproof {} interface Shoots {} class .....
  • Java编程思想/Android架构

    千次阅读 2015-07-01 17:59:12
    http://www.360doc.com/content/13/0817/08/6828497_307737703.shtml  http://zhidao.baidu.com/question/303285878.html?qbl=relate_question_1&word=%C3%E6%CF%F2%B6%D4%CF%F3%B5%C4%B1%E0%B3%CC%CB%BC%CF%EB
  • JAVA编程思想:附录A 使用非JAVA代码

    千次阅读 2007-09-24 14:38:00
    附录A 使用非JAVA代码JAVA语言及其标准API(应用程序编程接口)应付应用程序的编写已绰绰有余。但在某些情况下,还是必须使用非JAVA编码。例如,我们有时要访问操作系统的专用特性,与特殊的硬件设备打交道,重复...
  • Java编程思想》读书笔记 第五章、初始化与清理(一) 引言:Java采用了构造器,并额外提供了”垃圾回收器”。对于不再使用的内存资源,垃圾回收器将自动将其释放。 5.1用构造器确保初始化 (1)构造器名与类名...
  • 硅谷创业之父Paul Graham曾在《黑客与画家》中写道,“判断一种语言是否流行的条件是,一种免费的实现,一本相关书籍,以及语言所依附的计算机系统。”当然,Java也不例外。从 199...
  • Java-Java编程思想第四版 第十章 练习

    千次阅读 2018-02-18 02:14:43
    PS:(1)变量aa必须定义成Object,这样导入参数时Word类可以向上转型成Object,使toString()可以工作(2)toString()方法必须是public的(3)String word变量不能是static的,否则当它从aaaa变到cccc,指向它的a[0]~a[2...
  • 59.java编程思想——创建窗口和程序片 Swing 当我们的工作方法在AWT 中发生了巨大的改变后(如果可以回忆起很久以前,当Java 第 一次面世时SUN 公司曾声明Java 是一种“稳定,牢固”的编程语言),可能一直有Java ...
  • P116 public class Test{ public Test(){ System.out.println("Hello Word"); } public static void main(String[] args) { new Test(); } /** * 运行结果 Hello Word */ } 练习4:(1)为前一个...
  • 42.java编程思想——反射 运行期类信息 如果不知道一个对象的准确类型,RTTI 会帮助我们调查。但却有一个限制:类型必须是在编译期间已知的,否则就不能用RTTI调查它,进而无法展开下一步的工作。换言之,编译器...
  • 一、Java的RTTI  RTTI(Run-Time Type Identification,通过运行时类型识别)的含义就是在运行时识别一个对象的类型,其对应的类是Class对象,每个java里面的类都对应一个Class对象(在编写并且编译后),这个...
  • Java编程思想(第四版)*第二章 个人练习 创建一个类,它包含一个int域和一个char域, 他们都没有被初始化,将他们打印出来, 以验证java执行了默认初始化。 创建一个Hello,world程序,该程序只要输出这句话即可。 ...
  • 不过感觉这本书没有从一个语言的系统角度自上而下的展开,而是从理解的难易(自己觉得)由浅入深将Java中很多的细节娓娓道来;个人感觉这样对理解语言设计的本事没有太多益处,只是积累了更多的碎片,而对于实际使用...
  • 根据编程思想的例子类方法提取器,可以稍微了解反射的优点: //类方法提取器 package typeinfo; import java.lang.reflect.*; import java.util.regex.*; import static net.mindview.util.Print.*; public ...
  • 续《JAVA编程思想》学习备忘(第209页:Access Control)-2Interface and implementationAccess control is often referred to as implementation hiding.Wrapping data and methods within classes in combination...
  • String str2="word"; String str3=new String("hello"); testStr(str1, str2); System.out.println("--------------------------"); testStr(str1, str3); } public static void testStr(String s1,...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 15,380
精华内容 6,152
关键字:

java编程思想word

java 订阅