2016-06-18 99 views
0

我有一個方法使用類Region中的對象,因爲我需要掃描該對象的另一個方法使用此方法,因此我可以應用該方法。Java掃描對象

public void changeBusinessPermitTile(Region region){ 
     if(getRegion()==null) { 
      Region i; 
      Scanner scanner = null; 
      try { 
       System.out.print("Please insert the region: "); 
       scanner = new Scanner(System.in); 
       i = scanner.//this is the missing part 
       setRegion(i); 
      } finally { 
       if (scanner!=null) 
        scanner.close(); 
      } 
     } 
} 

所以我想的是,當我寫例如

Region region1 = new Region(Landscape.COAST); 
Region region2 = new Region(Landscape.HILL); 
Region region3 = new Region(Landscape.MOUNTAIN); 

這種方法應該能夠掃描當我寫REGION1,區域2或區3

+0

你會希望避免關閉,除非你的整個程序是使用'System.in'做到這一點已經被初始化的'System.in'掃描儀。 –

+0

所以我只壓制警告'資源泄漏:'掃描儀'永遠不會關閉'? – mpz

+0

此外,您的代碼看起來像可能將業務邏輯與用戶界面混合在一起。如果可能的話,這兩者應該分開放置。 –

回答

1

你可以閱讀LandscapeString並初始化實例,如

Region r = new Region(Landscape.valueOf(scanner.nextLine())); 

In此外,你可以創建自己的小池(Map<String, Region>),其中保存Region實例。它看起來像Flyweight pattern

if (map.get(scanner.nextLine()) == null) { 
    // create an instance and put it in the map 
} else { 
    // return old value from the map 
} 
+0

但不會創建一個新的區域對象嗎?因爲一旦我創建了區域1,區域2和區域3,每當我使用該方法時,我應該只使用其中一個對象。 – mpz

+0

@mpz,當你寫''region1''時,你希望得到'new Region(Landscape.COAST)'? – Andrew

+0

@AndrewTobilko如果你的意思是,每次它應該創建一個新區域的海岸則沒有,我想要的是竹葉提取能夠離開的說法區域上的空'changeBusinessPermitTile(空)'然後它應該問我插入它,所以我可以寫入region1,region2或region3作爲輸入。 – mpz

0

好吧,我想我明白你的問題,簡而言之,你試圖將一個區域與一個字符串聯繫起來。如果是這樣,那麼規範的解決方案是使用一個Map,比如通過使用抽象類型Map<String, Region>,你可能實例化爲HashMap<String, Region>。然後,您將使用put(String key, Region value)方法填充包含字符串/區域對的地圖,然後使用地圖的get(String key)方法根據關鍵字String獲取Region。

我仍然擔心你的整體程序設計,但這是一個單獨的問題。

例如:

import java.util.HashMap; 
import java.util.Map; 
import java.util.Scanner; 

public class RegionFun { 
    public static void main(String[] args) { 
     Map<String, Region> regionMap = new HashMap<>(); 
     regionMap.put("coast", new Region(Landscape.COAST)); 
     regionMap.put("Hill", new Region(Landscape.HILL)); 
     regionMap.put("mountain", new Region(Landscape.MOUNTAIN)); 

     Scanner scanner = new Scanner(System.in); 
     System.out.print("Enter location of region: "); 
     String input = scanner.nextLine().toLowerCase(); 

     Region region = regionMap.get(input); 

     System.out.println("Selected Region: " + region); 
    } 
} 

enum Landscape { 
    COAST, HILL, MOUNTAIN 
} 

class Region { 
    private Landscape landscape; 

    public Region(Landscape landscape) { 
     this.landscape = landscape; 
    } 

    @Override 
    public String toString() { 
     return "Region [landscape=" + landscape + "]"; 
    } 
}