2013-03-18 80 views
1

因此,在我的第五行代碼[if(length == 2 || 1)]中,我收到一條錯誤消息,未定義爲參數類型boolean,int。關於我的語法有什麼問題以及我如何解決它的任何想法?謝謝!在帶有字符串長度方法的「if」語句中使用「或」語句

//Write a program that translates a letter grade into a number grade. Letter grades are 
//A B C D F, possibly followed by + or -. Their numeric values are 4, 3, 2, 1, and 0. 
//There is no F+ or F-. A + increases the numeric value by 0.3, a - decreases it by  0.3. 
//However, an A+ has the value 4.0. All other inputs have value –1. 
//Enter a letter grade: 

//使用類使用方法getNumericGrade評分。

public class Grade { 
private double grade = 0.0; 
public double getNumericGrade(String letterGrade){ 
    int length = letterGrade.length(); 
    if(length == 2 || 1){ 
     char startChar = letterGrade.charAt(0); 
     char endChar = letterGrade.charAt(1); 
     switch(startChar){ 
     case 'A': 
      this.grade = 4.0; 
      break; 
     case 'B': 
      this.grade = 3.0; 
      break; 
     case 'C': 
      this.grade = 2.0; 
      break; 
     case 'D': 
      this.grade = 1.0; 
      break; 
     case 'F': 
      this.grade = 0.0; 
      break; 
     default: 
      this.grade = -1; 
     } 
    if(length == 2){ 
     switch(endChar){ 
     case '-': 
      this.grade = this.grade - .3; 
      break; 
     case '+': 
      if(startChar != 'A'){ 
      this.grade = this.grade + .3; 
      } 
      break; 
     default: 
      this.grade = -1; 
     } 
    } 
    if(startChar == 'F' && length != 1){ 
     this.grade = -1; 
    } 
    }else{ 
     this.grade = -1; 
    } 
    return this.grade; 
} 

}

+1

應該是'長度== 2 ||長度== 1'。無法在條件中爲1進行2。 – squiguy 2013-03-18 00:55:57

回答

3

這意味着||運營商並不需要一個布爾值和一個int,你必須給它兩個布爾表達式。

if(length == 2 || length == 1) 
+0

非常感謝,工作! – 2013-03-18 00:57:05

+1

+1速度(有兩種類型的人:快速和沒有) – Bohemian 2013-03-18 00:57:15

1

你想說的是if(length == 1 || length == 2)。你現在正在做的是說如果(長度= 2或1)。前者涉及兩個可以評估真假的邏輯陳述,後者一方面包含邏輯陳述,另一方面包含整數。

計算機不會將長度== 2或1解釋爲「如果長度是一個或兩個,則返回true」,而是解釋爲「(如果長度等於二則返回true」)或(整數1)「。

0

你可以這樣做:

if (Arrays.asList(1,2,3).contains(l.lenghth)) 
    // code 
+0

你好。我注意到你是一個新用戶。請閱讀[回答]。 – 2013-03-18 05:49:39

+0

我的回答有什麼問題? – Sascha 2013-03-18 07:13:29

+0

這沒有錯,它不是*** ***。一般來說,你付出的努力越多,獎勵就越多。我看到你是新的,因此我將你重定向到一個頁面,專門告訴你這個網站的注意事項。 – 2013-03-18 07:42:20