简体   繁体   English

连接两个 if else 语句时如何修复错误?

[英]How do I fix error when connecting two if else statements?

I am new at java and creating my first project which is a calculator using intellij.我是 java 的新手,并创建了我的第一个项目,即使用 intellij 的计算器。 I have created two if else statements the first one takes the average given by the user and turns it into a grade.我创建了两个 if else 语句,第一个语句取用户给出的平均值并将其转换为等级。 The second one is supposed to take the grade then turn it into a gpa.第二个应该拿成绩然后把它变成gpa。 i have declared String grade;我已经声明了字符串等级; and String gpa.和字符串 gpa。

  if (avg >= 90.0 ) {
    grade = "A";
  } else if (avg >=80.0) {
    grade = "B";
  } else if (avg >=70.0){
    grade = "C";
  } else if (avg >=60.0) {
    grade = "D";
  } else {
    grade = "F";
  }
  System.out.println("Grade is  " + grade );
  if (grade = A ) {      
    gpa = "4.0";        
  } else if (grade = B) { 
    gpa = "3.0";        
  }

Edit: The grade equals solution fixes the first error with the red underline but it doesn't compile.编辑:等级等于解决方案用红色下划线修复了第一个错误,但它没有编译。 So I ended up using a switch statement instead in order to get two print statements.所以我最终使用了 switch 语句来获得两个打印语句。

if (avg >= 90.0 ) {
   grade = "A";
} else if (avg >=80.0) {
   grade = "B";
} else if (avg >=70.0) {
   grade = "C";
} else if (avg >=60.0) {
   grade = "D";
} else {
   grade = "F";
}
System.out.println("Grade is  " + grade );
if (grade.equals("A")) {      
   gpa = "4.0";        
} else if (grade.equals("B")) { 
   gpa = "3.0";        
}

Several problems:几个问题:

if (grade = A ) 

to check if it's equal, you should use == (for comparing references) or equals for string.要检查它是否相等,您应该使用 == (用于比较引用)或equals字符串。

A is not a variable, but a string you want to compare to, so it should be "A" A不是变量,而是要比较的字符串,所以应该是"A"

there's no really point in doing it in two separate if's.在两个单独的 if 中做这件事并没有真正的意义。 do it once:做一次:

if (avg >= 90.0 ) {
   grade = "A";
   gpa = "4.0";
} else if (avg >=80.0) {
   grade = "B";
   gpa = "3.5";
} else if (avg >=70.0){
...
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM