<Head First Java>学习笔记--第五章:编写程序

这一章作者开始带我们写稍微复杂一点点的程序了。暂不去讨论里面的程序,我们来说说新学到的知识。

加强版的for循环和String转化为int

加强版的for循环

String转化为int

好的,为了测试上面新学到的两个知识,写了如下代码TestForStatement.java:

public class TestForStatement{

    public static void main(String[] args)
    {
        int i = 0;
        int number = 0;
        String[] nameArray = new String[3];
        String[] numArray = new String[3];

        nameArray[0] = "zero";
        nameArray[1] = "one";
        nameArray[2] = "two";

        numArray[0] = "0";
        numArray[1] = "1";
        numArray[2] = "2";

        // 普通版for循环
        System.out.println("Standard for statement:");
        for(i=0; i<nameArray.length; i++)
        {
            System.out.println("StringName: " + nameArray[i]);
            number = Integer.parseInt(numArray[i]);
            System.out.printf("IntNum: %d\n",  number++);

            // 不能这么做,因为Integer.parseInt()返回的是一个值而不是变量,无法进行++操作
            //System.out.printf("IntNum: %d\n", (Integer.parseInt(numArray[i]))++);
        }

        System.out.println();

        // 加强版for循环
        System.out.println("More stronger for statement:");
        for(String name : nameArray)
        {
            System.out.println("StringName: " + name);
        }

        for(String num : numArray)
        {
            number = Integer.parseInt(num);
            System.out.printf("IntNum: %d\n", number++);
        }
    }
}

运行结果如下:

运行结果


普通版和加强版for循环的比较

普通版for循环:

for(i=0; i<nameArray.length; i++)

加强版for循环

for(String name : nameArray)

加强版的for循环较之于普通版主要是省略掉了循环结束标记和自增操作。使用加强版for循环,程序知道什么时候结束(重复执行至所有的元素都被执行为止),自动每次”加1”跳到下一个元素。且一个加强版的for循环只能遍历一个集合,如果想遍历多个集合,就得有多个加强版for循环。这样一看,加强版只适用于依次遍历一个集合中所有的元素这种场合中,你不能只想执行编号为奇数或偶数的元素。但是,之所以成为加强版for循环是因为它用起来方便,肯定是要经常使用到类似的情况所以才会出一个加强版的for循环的。
与此相比较的普通版for循环有更大的灵活性,从哪个位置开始循环、何时停止循环、增量是多少都很方便控制,唯一要注意千万不能越界获取元素,那样总会出现不可预知的后果


String转换为int

我们新学到了一个方法:Integer.parseInt()。那么这个具体是什么呢?怎么使用呢?怎么实现的呢?

Java API文档

带着这些疑问,我们开始查找Integer这个类。Java 中文API文档Java英文API文档都对这个类有详细的说明。在以后的学习中,肯定是经常要去查看这两份API文档的。
通过这两份API文档,我们可以查找到Integer这个类的相关信息。
1> 位于哪个包和接口信息

中文信息

英文信息

2> 该类的简要信息

中文简要信息

英文简要信息

3> 该类的字段(属性)摘要信息

中文字段摘要

英文字段摘要

4> 该类的构造方法摘要信息

中文构造方法摘要

英文构造方法摘要

5> 该类的方法摘要信息

中文方法摘要

英文方法摘要

6> 该类的属性、方法的详细信息
详细信息都罗列在摘要的后面,这可不能错过。


Java 源码

通过Java API文档我们知道Integer类中parseInt()方法的使用方法:

parseInt方法

顾名思义,Java API文档只提供接口信息,并没有提供方法的具体实现是怎么做的?那么我们想看方法的具体实现怎么办呢?
答案是在安装目录下有源码,以我的为例是在:%JAVA_HOME%\jdk1.7.0_21\src_zip 这个文件,解压改文件找到对应的类就可以了。
下面是parseInt(String s)的源代码:

/**
     * Parses the string argument as a signed decimal integer. The
     * characters in the string must all be decimal digits, except
     * that the first character may be an ASCII minus sign {@code '-'}
     * (<code>'&#92;u002D'</code>) to indicate a negative value or an
     * ASCII plus sign {@code '+'} (<code>'&#92;u002B'</code>) to
     * indicate a positive value. The resulting integer value is
     * returned, exactly as if the argument and the radix 10 were
     * given as arguments to the {@link #parseInt(java.lang.String,
     * int)} method.
     *
     * @param s    a {@code String} containing the {@code int}
     *             representation to be parsed
     * @return     the integer value represented by the argument in decimal.
     * @exception  NumberFormatException  if the string does not contain a
     *               parsable integer.
     */
    public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }

下面是parseInt(String s, int radix)的源码:

/**
     * Parses the string argument as a signed integer in the radix
     * specified by the second argument. The characters in the string
     * must all be digits of the specified radix (as determined by
     * whether {@link java.lang.Character#digit(char, int)} returns a
     * nonnegative value), except that the first character may be an
     * ASCII minus sign {@code '-'} (<code>'&#92;u002D'</code>) to
     * indicate a negative value or an ASCII plus sign {@code '+'}
     * (<code>'&#92;u002B'</code>) to indicate a positive value. The
     * resulting integer value is returned.
     *
     * <p>An exception of type {@code NumberFormatException} is
     * thrown if any of the following situations occurs:
     * <ul>
     * <li>The first argument is {@code null} or is a string of
     * length zero.
     *
     * <li>The radix is either smaller than
     * {@link java.lang.Character#MIN_RADIX} or
     * larger than {@link java.lang.Character#MAX_RADIX}.
     *
     * <li>Any character of the string is not a digit of the specified
     * radix, except that the first character may be a minus sign
     * {@code '-'} (<code>'&#92;u002D'</code>) or plus sign
     * {@code '+'} (<code>'&#92;u002B'</code>) provided that the
     * string is longer than length 1.
     *
     * <li>The value represented by the string is not a value of type
     * {@code int}.
     * </ul>
     *
     * <p>Examples:
     * <blockquote><pre>
     * parseInt("0", 10) returns 0
     * parseInt("473", 10) returns 473
     * parseInt("+42", 10) returns 42
     * parseInt("-0", 10) returns 0
     * parseInt("-FF", 16) returns -255
     * parseInt("1100110", 2) returns 102
     * parseInt("2147483647", 10) returns 2147483647
     * parseInt("-2147483648", 10) returns -2147483648
     * parseInt("2147483648", 10) throws a NumberFormatException
     * parseInt("99", 8) throws a NumberFormatException
     * parseInt("Kona", 10) throws a NumberFormatException
     * parseInt("Kona", 27) returns 411787
     * </pre></blockquote>
     *
     * @param      s   the {@code String} containing the integer
     *                  representation to be parsed
     * @param      radix   the radix to be used while parsing {@code s}.
     * @return     the integer represented by the string argument in the
     *             specified radix.
     * @exception  NumberFormatException if the {@code String}
     *             does not contain a parsable {@code int}.
     */
    public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        /*
         * WARNING: This method may be invoked early during VM initialization
         * before IntegerCache is initialized. Care must be taken to not use
         * the valueOf method.
         */

        if (s == null) {
            throw new NumberFormatException("null");
        }

        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }

        if (radix > Character.MAX_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " greater than Character.MAX_RADIX");
        }

        int result = 0;
        boolean negative = false;
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);

                if (len == 1) // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            multmin = limit / radix;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                digit = Character.digit(s.charAt(i++),radix);
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        return negative ? result : -result;
    }

说实话,在没看到这两段源代码之前,我天真的以为String类型转换为int类型很简单。无非就是计算String的长度,然后根据数字在元素中的位置乘以相应的倍数即可。唉!太天真了,在源码中有对传入参数的有效性做判断、有对数值范围做判断,然后根据情况抛出对应的异常。你看人家想得多周到。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值