2014-11-22 32 views
4

我創建了一個類來讀取用戶輸入。我正在使用掃描儀來獲取用戶輸入並對其進行消毒。當使用掃描儀的對象,它打動了我與這2種方法將是最佳實踐的一個問題:在類或方法中實例化Java掃描器

  • 要創建一個類&實例化該掃描儀參考 - >使用它在每個方法

    private Scanner sc = new Scanner(System.in); 
    
    public int readInt() { 
    
        int input = sc.nextInt();   
        // some code to restrict input to integers only 
        return input;  
    
    } 
    
    public int readDouble() { 
    
        int double = sc.nextDouble(); 
        // some code to restrict input to double only 
        return input;  
    
    } 
    
  • 要創建一個掃描器引用的類 - >實例化它在每個方法 - >在每個方法中使用它

    private Scanner; 
    
    public int readInt() { 
    
        sc = new Scanner(System.in); 
    
        int input = sc.nextInt();   
        // some code to restrict input to integers only 
        return input;  
    
    } 
    
    public int readDouble() { 
    
        sc = new Scanner(System.in); 
    
        int double = sc.nextDouble(); 
        // some code to restrict input to double only 
        return input;  
    
    } 
    

    想象的情形WH這個類的對象將在另一個類中創建,readInt()或readDouble()將被多次調用。在這種情況下,從安全性和記憶的角度來看,上述兩種方法中哪一種更實用?

或者作爲其中一條評論建議以上都不實用,最好的方法是將掃描儀對象作爲參數傳遞給每個方法?

+3

如何在想要讀取的方法中創建掃描器,並將其作爲參數傳遞給方法?這將是最好的選擇,國際海事組織。 – 2014-11-22 14:37:02

+0

在第一種情況下,要小心'nextInt'然後加'nextLine'(如果你的代碼中有'readLine') – Maroun 2014-11-22 14:37:10

+0

@JBNizet謝謝。這確實是一個很好的選擇。然而,對於更優雅的代碼,我想照顧這個類中的所有Scanner對象,並只在這裏導入它。 – muradbax 2014-11-22 14:56:39

回答

1

這個問題很好,我想宣佈我的意見。一方面,在單線程模型中,在類中創建Scanner引用的方法等同於實例化它的方法。另一方面,在多線程模型中,在類中創建掃描器相關性 的方法可能無法得到正確的答案。