谁能给我介绍下assert的用法,以及解释下一道题目

huosidun0302 2009-06-30 09:16:33
1首先先介绍下asser的用法吧,举个小例子说明下!
2jdk的api中有assert吗?

下面是一道题,大家帮我解释下
23.int z=5;
24.
25. public void stuff1(int x) {
26. assert (x> 0);
27. switch(x) {
28. case 2: x= 3;
29. default: assert false; } }
30.
31. private void stuff2(int y) { assert (y < 0); }
32.
33. private void stuff3() { assert (stuff4()); }
34.
35. private boolean stuff4() { z = 6; return false; }
Which is true?
A. All of the assert statements are used appropriately.
B. Only the assert statement on line 31 is used appropriately.
C. The assert statements on lines 29 and 31 are used appropriately.
D. The assert statements on lines 26 and 29 are used appropriately.
E. The assert statements on lines 29 and 33 are used appropriately.
F. The assert statements on lines 29, 31, and 33 are used
appropriately.
G. The assert statements on lines 26, 29, and 31 are used
appropriately.
...全文
159 13 打赏 收藏 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
m_angle_m 2009-09-16
  • 打赏
  • 举报
回复
其他的统一6楼说法
m_angle_m 2009-09-16
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 wangju309 的回复:]
assert是个断言语句吧,应该相当于junit中的assertEqual和assertTrue等方法
[/Quote]

答案也该是C
在swith中使用的目的是为了检测是否会进入default 前提是程序本意不想进入default 就要在default中用断言 assert false 如果进入了说明程序流程有问题 这是assert的一种检测方式
huosidun0302 2009-07-29
  • 打赏
  • 举报
回复
自己顶了
  • 打赏
  • 举报
回复
从来就没用过这个关键词,呵呵。
bigbug9002 2009-07-14
  • 打赏
  • 举报
回复
学习来了.
holsten32 2009-07-14
  • 打赏
  • 举报
回复
帮顶
huosidun0302 2009-07-14
  • 打赏
  • 举报
回复
lovecj6185 2009-07-02
  • 打赏
  • 举报
回复
[Quote=引用楼主 huosidun0302 的帖子:]
23.int z=5;
24.
25. public void stuff1(int x) {
26. assert (x> 0);
27. switch(x) {
28. case 2: x= 3;
29. default: assert false; } }
30.
31. private void stuff2(int y) { assert (y < 0); }
32.
33. private void stuff3() { assert (stuff4()); }
34.
35. private boolean stuff4…
[/Quote]

首先,这道题问的是哪些行的断言的使用是适当的,而并不是能够通过编译的。
实际上,代码是可以编译通过的。
问题是要找出哪些的用法是恰当的。

断言的使用,有如下几个原则:
1.不要使用断言验证公共方法的参数。
2.可以使用断言验证私有方法的参数。
3.不要使用断言验证命令行参数
4.在公共方法内,可以使用断言检查从不会发生的情况
比如,switch中的default
像下面的应用就是适当的

switch(x){
case 1:
y=1;
break;
case 2:
y=2;
break;
default:
assert false;
}

你可以假设x为1或者2,所以default可以认为是不可到达的,这个时候可以使用断言

5.不要使用可能产生副作用的断言
也就是断言表达式应该使程序保持在进入它之前的状态。

所以,根据上述5点,
可以判断出
26行的断言使用不恰当,因为它是用来验证了一个公共方法。
29行的也不恰当,因为28行的后面并没有break语句,也就是说如果进入了case2,则一定会执行default的内容
31行的使用是正确的,因为用断言验证的是一个私有的方法
33行的使用是不恰当的,因为stuff4()肯定返回一个false,所以33行肯定会抛出AssertionError,这个违反了第5个原则

综上所述,偶认为答案是 B
myairland 2009-07-01
  • 打赏
  • 举报
回复
http://www.ibm.com/developerworks/cn/java/l-javaassertion/index.html

里面说的很详细,要仔细看哦,要不学不到东西的
tfsict2008 2009-07-01
  • 打赏
  • 举报
回复
选择 c 吧
wangju309 2009-07-01
  • 打赏
  • 举报
回复
assert是个断言语句吧,应该相当于junit中的assertEqual和assertTrue等方法
huosidun0302 2009-07-01
  • 打赏
  • 举报
回复
详细点啊!!!高手们
huosidun0302 2009-06-30
  • 打赏
  • 举报
回复
自己顶了!!

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧