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
- for循环不加退出条件、equals的作用
- for循环不加退出条件、equals的作用
- Python for, while循环后面加else的作用
- for循环的条件冗余
- for循环,循环条件
- Python学习笔记--for, while循环后面加else的作用
- 入口条件循环和退出条件循环
- for each循环的作用
- 退出双层的for循环的方法
- for循环退出方法,带冒号:的退出等
- for循环判断条件中尽量不写函数
- java退出for循环
- 用函数作为for循环的条件
- for循环的判断条件应注意!
- 自加作为循环的执行条件时的注意事项
- 错误锦集一:循环退出条件(递归退出条件)
- C++的for循环作用域
- for循环变量作用域的范围
- 百人团队敏捷转型日记 第一集 架构师没了、版本管理的蜕变
- HBase Snapshot解析
- 日经春秋 20160313
- Windows 中 cmd 下 FTP 命令的简单使用
- 第三周项目4-穷举法-委派任务
- for循环不加退出条件、equals的作用
- volatile关键字
- 剑指offer代码分析——面试题13在O(1)内删除链表结点
- BestCoder Round #75 King's Game
- SIM900B GPRS模块————打电话、发短信、接电话
- 使用GitHub pages + Hexo 快速搭建个性化博客(一)-部署Hexo默认blog模板至远程GitHub
- activity页面切换动画
- python 2.7 - 安装
- Smartisan T1 的传感器全家福