-5

编写一个名为的方法,该方法inputBirthday接受控制台的 Scanner 作为参数并提示用户输入出生年月日,然后以合适的格式打印出生日期。这是与用户的示例对话:

On what day of the month were you born? 8
What is the name of the month in which you were born? May
During what year were you born? 1981
You were born on May 8, 1981. You're mighty old!

所以这就是我所做的:

import java.util.Scanner;

public static void inputBirthday(int month,String day,int year){
    Scanner sc=new Scanner(System.in);
    System.out.print("On what day of the month were you born?");
    month=sc.nextInt();

    System.out.print("What is the name of the month in which you were born?");
    day=sc.nextLine();

    System.out.print("During what year were you born?");
    year=sc.nextInt();  
}

我的代码编译失败。有人可以给我一些提示,我会自己尝试一下。

4

4 回答 4

4

类需要声明。Java 是一种OO语言,因此必须使用类:

class MyClass {
   public static void inputBirthday(int month, String day, int year) {
      ...
   }
}

inputBirthday可以替换为一种main方法,该方法将为您的类提供一个运行程序的入口点。

于 2013-02-10T17:07:43.657 回答
2

你需要把你的方法封装在inputBirthday(...)里面class

喜欢:

class Birthday{
     public static void inputBirthday(int month, String day, int year) {
      // .... rest of the code ....
  }
}
于 2013-02-10T17:09:18.020 回答
2

Java每一件事上都需要在课堂上。

例如

import java.util.Scanner;
public class BirthdayClass{
  public static void inputBirthday(){
    Scanner sc=new Scanner(System.in);
    System.out.print("On what day of the month were you born?");
    int month=sc.nextInt();

    System.out.print("What is the name of the month in which you were born?");
    int day=sc.nextLine();

    System.out.print("During what year were you born?");
    int year=sc.nextInt();

  }
 // This is main method which is called when class is loaded
 public static void main(String[] args){
   BirthdayClass.inputBirthday();
 }
}

使用编译程序javac BirthdayClass.java,然后使用java BirthdayClass.

此外,您不需要传递day,monthyear作为参数,因为您在方法中输入。相反,您应该在方法中声明它们。

于 2013-02-10T17:12:44.270 回答
0

我的建议是回去阅读你书中的第一章,你需要知道这些基本的东西才能做任何事情。每个程序在某个地方都需要一个 main 方法,通常在一个类中,几乎没有其他东西。减轻调试的痛苦。但是,如果您只是为学校做一些小练习,只需使用这个基本结构。

如果练习这么说,显然把它放在一个方法中,并在 main 方法中调用该方法。如果你在一个类中拥有它,你只会构建它的对象,但你可能在课堂上还不够了解 OOP 部分。

className {

    public static void main(String[] args) {
        // your code here.    
    }


} // end of class.
于 2013-02-10T19:09:11.243 回答