本人初学java,想请教大家关于参数的问题
一下代码是link list的find 方法public Link find(int key)
{
Link current = first;while (current.iData != key)
{
if (current.next ==null)
{
return null;
}else
{
current= current.next;
}
}
return current;
}main函数如下
public class LinkList2App
{
public static void main (String args[])
{
Link f = theLinkList.find(43);
if (f !=null)
{
System.out.println("Found link with key" + f.iData);
}
else
{
System.out.println("cannot find the key" );
}
中间省略了 insert等方法,整个程序是可以run的。
问题:
1. 如果把
else
{
System.out.println("cannot find the key" );
}
改成
else
{
System.out.println("cannot find the key"+f.iData );
}
编译成功,但是运行时,会有异常
2. 如果把
else
{
System.out.println("cannot find the key" );
}
改成
else
{
System.out.println("cannot find the key"+key );
}
编译出错,找不到变量 key。为什么会出现上述两种错误, 如果想输出 "cannot find the key 加上key的值” 应该如果修改。谢谢~
一下代码是link list的find 方法public Link find(int key)
{
Link current = first;while (current.iData != key)
{
if (current.next ==null)
{
return null;
}else
{
current= current.next;
}
}
return current;
}main函数如下
public class LinkList2App
{
public static void main (String args[])
{
Link f = theLinkList.find(43);
if (f !=null)
{
System.out.println("Found link with key" + f.iData);
}
else
{
System.out.println("cannot find the key" );
}
中间省略了 insert等方法,整个程序是可以run的。
问题:
1. 如果把
else
{
System.out.println("cannot find the key" );
}
改成
else
{
System.out.println("cannot find the key"+f.iData );
}
编译成功,但是运行时,会有异常
2. 如果把
else
{
System.out.println("cannot find the key" );
}
改成
else
{
System.out.println("cannot find the key"+key );
}
编译出错,找不到变量 key。为什么会出现上述两种错误, 如果想输出 "cannot find the key 加上key的值” 应该如果修改。谢谢~
System.out.println("Found link with key" + f.iData);
}
else {
System.out.println("cannot find the key" );
}
else 分支是f=null的情况,修改后,让null去调.iData()方法,肯定空指针嘛2else {
System.out.println("cannot find the key"+key );
}你这里并没有将key定义为参数,所以编译时找不到key,前面将key定义下,然后引用就可以了。