A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 马睿 中级黑马   /  2012-9-14 18:24  /  1805 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public boolean odd(int i)
  2. {
  3.      return i % 2 == 1;
  4. }

复制代码
会报错,为什么?

5 个回复

倒序浏览
目测没有错,能发下错误提示吗
回复 使用道具 举报
public static boolean odd(int i)
         
        {
         
             return i % 2 == 1;
         
        }

你加个静态试试
回复 使用道具 举报
public class Demo {
        public boolean odd(int i)
        {
                return i % 2 == 1;
        }

        public static void main(String[] args)
        {
                Demo demo = new Demo();
                System.out.println(demo.odd(10));
                System.out.println(demo.odd(9));
        }
}
回复 使用道具 举报
public class Demo {
        public boolean odd_1(int i)
        {
                return i % 2 == 1;
        }
        public static boolean odd_2(int i)
        {
                return i % 2 == 1;
        }
        public static void main(String[] args)
        {
                Demo demo = new Demo();               
                System.out.println(demo.odd_1(10));  //调用方式1
                System.out.println(demo.odd_1(9));

               
                System.out.println(Demo.odd_2(10));//调用方式2
                System.out.println(Demo.odd_2(9));

        }
}
回复 使用道具 举报
试试这种方式呢:
class Test {
        public static void main(String[]  args) {
        odd(7);
}

       public static void odd(int i) {
            if(i % 2 == 1) {
                System.out.println(i+"是奇数");
           }else {
               System.out.println(i+"是偶数");
           }
       }
}

如果是主函数调用的你方法,那么你定义的方法也必须是静态的;因为静态方法只能访问静态成员,
非静态方法既可以访问静态,也可以访问非静态。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马