回 帖 发 新 帖 刷新版面

主题:一个判断闰年的程序...

以下是自己编写的判断闰年的程序,有什么地方写错了?请指点!!!

import java.io.*;
public  class year{
 public boolean isLeapYear(int i){
   if((i%4==0&&i%100!=0)||(i%400==0))
   return true;
   else 
   return false;
 }
}

public class leapyear{
 int i;
  public void main(String[] args)throws IOException{
    BufferedReader x=new BufferedReader(new InputStreamReader(System.in));   
    i=Integer.parseInt(x.readLine());
    boolean judge=year.isLeapYear(i);
    System.out.println("Is it a Leap Year? "+judge);
  }   
}

回复列表 (共5个回复)

沙发


import java.io.*;
class year{
 public static boolean isLeapYear(int i){
   if((i%4==0&&i%100!=0)||(i%400==0))
   return true;
   else 
   return false;
 }
}

public class leapyear{
 public static int i;
  public static void main(String[] args)throws IOException{
      
    BufferedReader x=new BufferedReader(new InputStreamReader(System.in));   
    i=Integer.parseInt(x.readLine());
    boolean judge=year.isLeapYear(i);
    System.out.println("Is it a Leap Year? "+judge);
}
}
[em12]

板凳

import java.io.*;

public class year{
 public static boolean isLeapYear(int i){  //通过类名调用的方法必须为静态的
   if(i%4==0&&i%100!=0||i%400==0)
   return true;
   else 
   return false;
 }
}

class leapyear{

  public static void main(String[] args)throws IOException{
    BufferedReader x=new BufferedReader(new InputStreamReader(System.in));   
   int i=Integer.parseInt(x.readLine());  // i 作为局部变量而不必作属性
    x.close();
    boolean judge=year.isLeapYear(i);
    System.out.println("Is it a Leap Year? "+judge);
  }   
}

//一个JAVA源文件中只能有一个public 类,并且类名必须与文件名相同。

3 楼

而且java规范中类名开头一般是大写的,如果你Year类不声明成static,那么你在Leapyear中要调用时要声明Year类的对象

Year year = new Year();
boolean judge=year.isLeapYear(i);

4 楼

总结起来最关键一点,如果想boolean judge=year.isLeapYear(i);这么用,必须把isLeapYear()方法设为静态的,这样才能直接用类名调用,不然就得创建一个year类的对象.
另外用了输入流之后最好将其关闭,如上x.close().

5 楼

JAVA起跑线 一起学习交流群  12536284

我来回复

您尚未登录,请登录后再回复。点此登录或注册