2017-09-01 42 views
-3

所以即時通訊非常新的Java和創造的東西學校。 我的問題是最後一個If語句我做了比較字符串,我明白!=或> = does not工作,但我不明白用什麼來代替它。任何幫助?遇到了一個問題,我的Java程序

我試過查找正確的方式來使用該行,但我只是沒有真正明白什麼時候比較這兩個字母的確切人人都說。

package Secrets_hw2p1; 

/** 
* 
* @author secrets 
    */ 
    //importing Scanner 
    //import scanner 
    import java.util.Scanner; 
     public class secrets_hw2p1 { 

    /** 
    * @param args the command line arguments 
    */ 
     public static void main(String[] args) { 
     // TODO code application logic here 

    //Creating the Scanner object 
    Scanner input = new Scanner (System.in); 
    //getting students goal grade 
    System.out.println("What is your Goal Letter Grade? "); 
    String goalGrade = input.next(); 

    //Enter assignment scores. and read scores 
    System.out.println("Please enter in your two assignment scores followed" 
    +"by your two exam scores one at a time followed by enter "); 
    float assignment1 = input.nextFloat(); 
    float assignment2 = input.nextFloat(); 
    float exam1 = input.nextFloat(); 
    float exam2 = input.nextFloat(); 

    //calculations of averages 
    double goal = assignment1 * .40 + assignment2 * .40 + exam1 * .30 + 
      exam2 * 0.30; 
    int grade; 
    //Calculate Letter grade 
    if (goal >= 90) 
     grade = 'A'; 
    else if (goal >= 80) 
     grade = 'B'; 
    else if (goal >= 70) 
     grade = 'C'; 
    else 
     grade = 'D'; 



    //prompt the user for how they want there grade 
    System.out.println("Press 1 to display letter grade or press 2 to" 
    +"see if you met your goal "); 
    double number = input.nextDouble(); 

    //if user inputed 1 
    if (number == 1) 
     System.out.println ("Final grade:" + grade); 
    //if user inputed 2  
    if (number == 2) 
     if (goalGrade != grade) 
       System.out.println("You have not met or exceeded your goal" 
         +" grade"); 
     else if (c1.goalGrade >= grade) 
       System.out.println("You met or exceded your goal grade !"); 



    } 

} 
+0

'grade'應該是一個'String'。你應該使用'equals()'比較字符串。 – shmosel

+1

請注意''遇到了我的java程序問題''是一個StackOverflow問題的糟糕標題,因爲它告訴我們什麼都沒用。請考慮使用更多的信息性問題標題,這些標題總結了您的實際問題,因爲這樣做會幫助您獲得更好的幫助。欲瞭解更多信息,請瀏覽[遊覽],[幫助]和[如何提出一個好問題](http://stackoverflow.com/help/how-to-ask)部分,瞭解這個網站工作並幫助您改善當前和未來的問題,這可以幫助您獲得更好的答案。 –

+0

@shmosel或者可能使用'char',但絕對不是用於存儲字符文字的'int'。 –

回答

0

使用equals()方法來代替,改變grade類型String

String grade = ""; // changed datatype to String 

然後:

//if user inputed 2  
      if (number == 2) 
       if (goalGrade.equals(grade)) 
         System.out.println("You have not met or exceeded your goal" 
           +" grade"); 

閱讀:https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)

+0

如果您已將'grade'改爲'String',那麼您應該說明您的答案。採取逐字,你的答案也將失敗。 –

+0

@TimBiegeleisen完成。 –

0

因爲字符串是對象,你不能使用你的標準=或< =你將需要使用.equals方法。因此,而不是

if (goalGrade != grade) 

你想

if (!goalGrade.equals(grade)) 
+0

謝謝!我很欣賞它! –