2013-02-10 15 views
-5

編寫一個名爲​​的方法,該方法接受控制檯的掃描儀作爲參數,並提示用戶輸入出生月份,日期和年份,然後以合適的格式打印出生日。下面是與用戶的例子對話:Java初學者 - 使用參數和掃描儀

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(); 
} 

我的代碼無法編譯。有人可以給我一些提示,我會自己嘗試一下。

+1

提示?仔細閱讀編譯錯誤 - 它會告訴你它發生的文件和行號以及問題是什麼。 – duffymo 2013-02-10 17:08:40

+0

你的錯誤是什麼?假設你將它包裝在一個類中,它對我來說編譯得很好。 – MrHappyAsthma 2013-02-10 17:09:18

+0

錯誤是用import java.util.Scanner; – user2059072 2013-02-10 17:10:45

回答

4

類需要聲明。 Java是那麼使用類的OO語言是必須的:

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

你​​可以用一個main方法,這將使你的類從運行程序的入口點來代替。

2

您需要封裝的方法inputBirthday(...)class

,如:

class Birthday{ 
    public static void inputBirthday(int month, String day, int year) { 
     // .... rest of the code .... 
    } 
} 
+0

不,我不應該創建一個類。這是我在網上找到的練習題。我只需要創建該方法。 – user2059072 2013-02-10 17:09:58

+0

@ user2059072和'Java'方法不存在沒有類 – exexzian 2013-02-10 17:11:05

+0

方法必須在類中找到。 – MrHappyAsthma 2013-02-10 17:11:19

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運行它。

而且你不需要通過daymonthyear作爲參數,你在服用方法輸入。相反,你應該在方法中聲明它們。

0

我的建議是回頭閱讀你書中的第一章,你需要知道這些基本的東西能夠做任何事情。每個程序都需要一個主要的方法,通常在一個類中,其他方面都沒有。減輕調試的痛苦。但是,如果你只是爲了學校做小練習就簡單地使用這個基本結構。

很明顯,如果練習中這樣說,並在主要方法中調用該方法,將其放入方法中。如果你自己創建了某個類的對象,那麼你只需要構建它的某些對象,但是你可能還沒有足夠的時間去了解OOP部分。

className { 

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


} // end of class.