2011-11-16 55 views
3

我想運行下面的代碼。這是給我的錯誤簡單的Java錯誤代碼,同時編譯

運營商+未定義的參數類型的字符串,無效

public class CompStrings{ 

    String s1=null; 
    String s2=null; 

    public void testMethod(){ 


     s1 = new String("Hello"); 
     s2 = new String("Hello"); 
     String str3="abc"; 
     String str4 ="abc"; 
     /** 
     * == 
     */ 
     if(str3==str4){ 
      System.out.println("str3==str4 is true"); 
     }else{ 
      System.out.println("str3==str4 is false"); 
     } 

     if(str3.equals(str4)){ 
      System.out.println("str1.equals(str2) is true"); 
     }else{ 
      System.out.println("str1.equals(str2) is false"); 
     } 

     System.out.println(s1.hashCode()); 
     System.out.println(s2.hashCode()); 

     System.out.println(s1 + " equals " + s2 + " -> " + 
     s1.equals(s2)); 

     System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2)); 
     /*Integer i1 = new Integer(10); 
     Integer i2 = new Integer(10); 
     System.out.println(i1.hashCode()); 
     System.out.println(i2.hashCode()); 
     1)String s1="hello"; 
     String s2="hello"; 

     2)String s1 = new String("Hello"); 
     String s2 = new String("Hello"); 

     3)String s1="hello"; 
     string s2=s1; 

     **/ 

    } 
    public static void main(String argv[]){ 
     CompStrings obj= new CompStrings(); 
//  \System.out.println("Calling My Method"+ obj.testMethod()); 

    System.out.println("Hashcode for emp1 = " + obj.testMethod());// Here it gives Error 



    } 


    public boolean equals(Object o){ 
     String s = (String) o; 
     if (s1.equals(s)){ 
      return true; 
     }else{ 
      return false; 
     } 


     } 

     public int hashCode(){ 
     return s1.hashCode(); 

     } 

} 

回答

3

testMethod()不返回任何東西 - 所以你會希望得到的結果當你嘗試使用表達式testMethod()的值爲的任何的原因? (在這種情況下,你恰好在字符串連接中使用它,但你不能將它分配給變量,將它作爲參數等傳遞)。

聽起來像你真的想要它返回一個哈希碼,給定System.out.println呼叫的其餘部分。或者:

System.out.println("Calling testMethod"); 
obj.testMethod(); 
System.out.println("testMethod finished"); 
4

testMethod()顯然不返回任何東西,這就是爲什麼沒有什麼可打印。

1

您的testMethod()沒有返回類型,如果您希望以這種方式使用它,它必須返回一個String或另一個對象。我說Object,因爲Java中的所有對象都從Object繼承,因此將實現toString()。

+0

感謝每一個機構 –

1

你的obj.testMethod()什麼都沒有返回(void)...所以你不能用字符串連接它。

試試這個:

System.out.println("Hashcode for emp1 = "); 
obj.testMethod(); 
0

首先,它會更清潔,這樣

字符串S1 =寫 「你好」; String s2 =「你好」;

但問題是,testMethod()不返回一個字符串....它什麼都沒有返回!

0

testMethod()應該返回String而不是void

或者說,不要把呼叫testMethod()System.out.println()