2013-12-03 60 views
1

我想創建新對象併爲其提供用戶輸入名稱。如何通過用戶輸入創建新對象名稱

示例用戶輸入「羅伯特」西港島線匹配:

Action robert = new Action(); 
robert.eat(); 

什麼我需要在程序中改變這樣我就可以創建新的對象與動態的名字嗎? 非常感謝。 我寫入下一個代碼:

import java.util.Scanner; 

public class Human { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     Scanner user_input = new Scanner(System.in); 

     String first_name; 
     System.out.print("Enter your first name: "); 
     first_name = user_input.next();//robert 

     System.out.println("You are " + first_name);//robert 

     Action first_name = new Action(); 
     Food orange = new Food(); 
     robert.eat(orange); 

    } 

} 
+0

對象通常不具有名稱。你在談論一個*變量*的名稱,這是完全不同的。如果你希望你的對象有一個名字,它應該有一個字段來記住它的名字,你應該把這個名字傳遞給構造函數。 –

+0

你錯了,YOu混合變量名和用戶名! –

+0

如果沒有人會在運行時看到它,爲什麼要給變量賦予一個動態名稱? – Math

回答

1

與其他語言不同,Java不能動態創建變量名稱。變量名稱在代碼中聲明。爲了實現你想要做的事情,請查看收藏的Map interface。這將允許您將給定名稱的用戶「映射」到某個值。

簡單的例子:

//1) Setup the mapping, 
//The first parameter to put() is the key (perhaps a user given name?) 
//and the second parameter is actual value you want to map for that key. 
//note that although I'm using a String as the key and a String as the value 
//You can use pretty much any object as the value. Keys are recommended to be 
//immutable objects (a String is a good one) 
Map<String,String> mMap = new HashMap<String,String>(); 
mMap.put("John", "Orange"); 
mMap.put("Steve","Apple"); 

//2) Once the map is setup, you can then retrieve values given a key: 
System.out.println("John's fruit is: "+mMap.get("John")); 

More info here

+0

非常感謝。 – user2879862

0

變量名不能被指定(創建)在運行時(動態地)。

0

這是不可能的。如何將Class對象的名稱聲明爲變量。

相關問題