2013-10-23 47 views
0

有誰知道如何比較參數與對象?我一直試圖按照最後一個問題給出的說明來做:http://prntscr.com/1zaq0y但是,似乎並不是。如何比較參數與Java中的對象?

public class Classification 
    { 
     String changes; 
     String rating; 
     String description; 

    Classification() 
    { 
     rating = "G"; 
     description = "Suitable for general audiences"; 
    } 

    Classification(String must) 
    { 
     if(must != "G" || must!= "PG" || must!="M") 
     { 
      throw new NullPointerException ("Not equal"); 
     } 
     rating = must; 
     if(rating == "G") 
     { 
      description = "Suitable for general audiences"; 
     } 
     if(rating == "PG") 
     { 
      description = "Parental guidance recommended"; 
     } 
     if(rating == "M") 
     { 
      description = "Suitable for mature audiences"; 
     } 
    } 

    Classification (int num, String para) 
    { 
     if(num!= 13 || num!= 15 || num!=16 || num!=18) 
     { 
      throw new IllegalArgumentException("Not equal"); 
     } 
     if(para==null) 
     { 
      throw new NullPointerException("String is null"); 
     } 
     if(num == 16) 
     { 
      rating = "R"; 
      description = para; 
     } 
     changes = rating + num; 
    } 

    void printClassification() 
    { 
     print("Rated " + rating + ": " + description); 
    } 

    void derestrict() 
    { 
     if(rating == "M") 
     { 
      rating = "PG";  
     } 
     if(rating == "PG") 
     { 
      rating = "G"; 
     } 
     if(rating == "G") 
     { 
      throw new IllegalArgumentException("G is least restrictive"); 
     } 
     if(changes == "R18") 
     { 
      changes = "R16"; 
     } 
     if(changes == "R15") 
     { 
      changes = "R13"; 
     } 
    } 

    Classification isLessRestrictive(Classification compare) 
    { 
     if(compare==null) 
     { 
      throw new NullPointerException ("Classification para is null"); 
     } 
     if(changes<compare) 
     { 
      return true; 
     } 
     return false; 
    } 
} 
+2

「參數」和「對象」之間的區別是什麼? –

回答

1

當比較String S IN的Java,你需要使用equals()

例如,

if(must != "G" || must!= "PG" || must!="M") 

應改爲

if(!"G".equals(must) || !"PG".equals(must) || !"M".equals(must)) 

而且

if(rating == "G") 

應該是這樣的:

if("G".equals(rating)) 
+1

不挑剔,因爲它不會影響答案,但是if(「G」.equals(rating))'更安全,因爲rating可以爲null。 – Radiodef

+0

@Radiodef嗯,好點。我會改變答案。 – nhgrif