Java中println函数的陷阱

前几日在学习Java的时候我家Smigoo遇到了一个小麻烦,怎么调试都无法通过,因此向我求救。在看了代码之后我也糊涂了,一时找不出问题出在什么地方。源代码如下,目的是为了测试代码点和代码单元的不同。

public class AA
{
    public static void main (String[] args)
    {
        String greeting="hello";
        int n=greeting.length();
        int m=greeting.codePointCount(0,greeting.length());
        System.out.println(n,m);
    }
}

一开始使用Notepad++编写源代码进行编译也是一样无法通过,奇怪了,JDK返回如下的错误。

println error Java中println函数的陷阱

从返回的提示上我怀疑println方法不能接受int类型的,但是从我做过的程序中确是能够接受int类型的参数的,这让我百思不得其解。于是放入Eclipse中调试。Eclipse就是强大,很快我便恍然大悟,然县错误所在,而且觉得十分的微不足道。将上述的代码放入Eclipse中后,在第8行提示一个错误,内容为:

the method println(int) int the type PrintStream is not applicable for the arguments (int,int)

注意加粗的部分,这就是说println直接受一个参数,并不是两个,如果想要打印两个参数的话必须使用两条println函数,其实也不算陷阱,JDK中就是这么设计的,但是在使用中并没有太注意。最终修改好的代码如下:

public class AB
{
public static void main (String[] args)
{
String greeting=”hello”;
int n=greeting.length();
int m=greeting.codePointCount(0,greeting.length());
System.out.println(n);
System.out.println(m);
}
}

这不得不说是个细小的错误,而且我居然没有察觉,也反映了我的Java水平还不够火候,还要继续学习。

Related Posts

4 comments:

  1. smigoo, 19. August 2008, 21:52

    呵呵 下次记住了~不过不知道其他两个什么情况哦~~

    Reply

     
  2. smallant, 16. April 2009, 21:36

    你为什么不用 println(m+” “+n);不就一起输出了吗?

    Reply

    SoleilNeon Reply:

    这样就在一行输出了,我是想分为两行

    Reply

     
  3. smallant88, 7. May 2009, 15:47

    没注意到,呵呵,我看了API当中,Println所有重载的方法都是接收一个参数。

    Reply

     

Write a comment: