遇到了我的java程序

时间:2017-09-01 03:08:12

标签: java

所以我对Java很新,并为学校创造了一些东西。 我的问题是我做的最后一个If语句比较字符串,我明白!=或> =不起作用,但我不明白用什么代替它。有什么帮助吗?

我已经尝试查找使用该线路的正确方法,但我真的不明白在比较两个字母时,每个人都在说些什么。

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 !");



    }

}

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

由于字符串是对象,因此您无法使用标准=或< =您将需要使用.equals方法。而不是

if (goalGrade != grade)

你想要

if (!goalGrade.equals(grade))