2011-09-19 45 views
0

誰能告訴我爲什麼我不能在我的互動面板中創建新的對象,或者爲什麼即使它被編譯該程序將無法運行?程序編譯,但不會跑,不能使用構造

import java.util.Random; 
/** 
* This program allows a user to enter their first and last name 
* and generate a random user id and default password. 
* 
* @author Brian Drake 
* @version 9/14/11 
*/ 

    public class UserID { 

     private String firstName; 

     private String lastName; 

     private String userId; 

     private String password; 


     public UserID(String first, String last) { 
     Random generator = new Random(); 

     firstName = first; 

     lastName = last; 

     userId = first.substring(0, 3) + last.substring(0, 3) 
      + generator.nextInt(1) + (generator.nextInt(7) + 3) 
      + generator.nextInt(10); 

     password = Integer.toString(generator.nextInt(10) + generator.nextInt(10) 
      + generator.nextInt(10) + generator.nextInt(10) 
      + generator.nextInt(10) + generator.nextInt(10)); 

     } 

     public String getId() { 
     return userId; 
     } 

     public String getPassword() { 
     return password; 
     } 

     public boolean setPassword(String randomPass) { 

     if (password.length() < 6 || password.length() > 6) { 
      randomPass = password; 

      return false;  
     } 

     else { 
      password = randomPass; 
     } 
     return true; 
     } 

     public void generateNewPassword() { 

     Random generator = new Random(); 

     password = Integer.toString(generator.nextInt(10) + generator.nextInt(10) 
      + generator.nextInt(10) + generator.nextInt(10) 
      + generator.nextInt(10) + generator.nextInt(10)); 

     } 

     public String toString(String first, String last) { 
     String output = firstName + " " + lastName + "\n"; 
     output += userId + "\n"; 
     output += password; 
     return output; 
     } 

    } 
+2

到底是什麼樣的「互動小組」? –

+1

定義「不會運行」。 –

回答

1

UserID類定義,你需要指定的參數值,同時創建一個對象(因爲你沒有創建無參數的構造函數) 。

UserID obj=new UserID("firstName","secondName"); 

編輯:

UserID

除此之外,你必須定義另一個類,其中包含一個入口點 - main()方法。

public class TestMain 
{ 
    public static void main(String []args) 
    { 
    UserID obj=new UserID("firstName","secondName"); 
    //Using obj reference variable, you can request to the object for any message. 
    System.out.println(obj.getId() + " " + obj.getPassword()); 
    } 
} 
+0

我應該在哪裏添加? – user951901

+0

@ user951901可能需要添加一個入口點 - 主要方法 – adatapost

5

它將無法運行,因爲沒有main方法

0

這不是一個程序。這只是一個課程,可能是一個課程的一部分。當你試圖運行它時,你應該得到一個NoSuchMethodException或類似的東西。

的程序基本上是中有一個public static void main(String[] args)的類。如果你想讓它自己運行(相對於其他代碼使用的組件),你需要添加一個。請注意,Java會調用這個方法來運行你的程序,所以它也需要做一些有用的事情。比如說,創建一個UserID並顯示它或者其他內容。 :)

0

您可以創建UserID類的對象。程序執行入口點Java是其main方法。

public static void main(String[] args){}