for循环不加退出条件、equals的作用

来源:互联网 发布:下载scratch软件 编辑:程序博客网 时间:2024/05/01 10:55
      for(int i=0;;i++){//用for循环遍历 搜索系统中是否有要借的图书         if((Books.books[i].name).equals(b)){             System.out.println("book:"+b);             break;//有则结束循环,没有则抛出一个异常         }     }     }catch(Exception e){         System.out.println("图书不存在!");//异常处理方式 重新输入图书            library1();     }

1.这个for循环用来遍历,其中没有加循环结束条件,因为在循环体内,如果i大于了所有图书,则会超过数组范围抛出异常。
我觉得这个设计挺巧妙。

但是可能有漏洞,不如加上length,但是这样的话就不能当没有找到时抛出异常。
解决方法:

private int searchBookByName() throws BookDoesNotExistException{        int i = 0;        System.out.println("请输入图书名称:");        c = new Scanner(System.in);        String s = c.next();        for(i = 0; i < book.length; i++){            if(s.equals(book[i])){                return i;            }        }        throw new BookDoesNotExistException("图书不存在!");    }

用了return语句及时跳出,如果没有则throw抛出异常。

2.这里逻辑判断相等用的equals,我喜欢用“==”,而根据equals的描述,它还能判断字符串是否相等。
那么,“==” 和 equals() 有什么区别呢?

==: 判断两个字符串在内存中首地址是否相同,即判断是否是同一个字符串对象

equals(): 比较存储在两个字符串对象中的内容是否一致

PS:字节是计算机存储信息的基本单位,1 个字节等于 8 位, gbk 编码中 1 个汉字字符存储需要 2 个字节,1 个英文字符存储需要 1 个字节。所以我们看到上面的程序运行结果中,每个汉字对应两个字节值,如“学”对应 “-47 -89” ,而英文字母 “J” 对应 “74” 。同时,我们还发现汉字对应的字节值为负数,原因在于每个字节是 8 位,最大值不能超过 127,而汉字转换为字节后超过 127,如果超过就会溢出,以负数的形式显示。

    /**     * Compares this string to the specified object.  The result is {@code     * true} if and only if the argument is not {@code null} and is a {@code     * String} object that represents the same sequence of characters as this     * object.     *     * @param  anObject     *         The object to compare this {@code String} against     *     * @return  {@code true} if the given object represents a {@code String}     *          equivalent to this string, {@code false} otherwise     *     * @see  #compareTo(String)     * @see  #equalsIgnoreCase(String)     */    public boolean equals(Object anObject) {        if (this == anObject) {            return true;        }        if (anObject instanceof String) {            String anotherString = (String) anObject;            int n = value.length;            if (n == anotherString.value.length) {                char v1[] = value;                char v2[] = anotherString.value;                int i = 0;                while (n-- != 0) {                    if (v1[i] != v2[i])                            return false;                    i++;                }                return true;            }        }        return false;    }
0 0
原创粉丝点击