我知道将私有变量设置为字符数据类型,但我只是好奇为什么这种技术不起作用。我已经制作了附带的模拟器。我也知道我不需要方法来做这个,但我正在尝试习惯用方法编码。
public class LetterGrade {
private String grade;
private double numGrade;
private String sign;
public LetterGrade(String grade)
{
}
public double sign()
{
if(grade.equals("A"))
numGrade=4.0;
else if(grade.equals("B"))
numGrade=3.0;
else if(grade.equals("C"))
numGrade=2.0;
else if(grade.equals("D"))
numGrade=1.0;
else if(grade.equals("F"))
numGrade=0.0;
else
System.out.println("");
if(grade.substring(0,1).equals("-"))
numGrade=numGrade-0.3;
else if(grade.equals("+"))
numGrade=numGrade+0.3;
if(grade.equals("A+"))
System.out.println(4.0);
if(grade.equals("F+"))
System.out.println("Not a valid input.");
if(grade.equals("F-"))
System.out.println("Not a valid input.");
return numGrade;
}
}
public static void main(String[]args)
{
Scanner input=new Scanner(System.in);
System.out.println("Enter a letter grade: ");
String grades=input.next();
LetterGrade grade=new LetterGrade(grades);
System.out.print("The numeric value is " );
System.out.println(grade.sign());
}
答案 0 :(得分:0)
您没有在构造函数中设置字段。像这样的东西
public LetterGrade(String grade)
{
this.grade = grade;
}
此外,我认为您希望String.startsWith(String)
和String.endsWith(String)
喜欢
public double sign() {
if (grade.startsWith("A")) {
numGrade = 4.0;
} else if (grade.startsWith("B")) {
numGrade = 3.0;
} else if (grade.startsWith("C")) {
numGrade = 2.0;
} else if (grade.startsWith("D")) {
numGrade = 1.0;
} else {
numGrade = 0.0;
}
if (grade.endsWith("-")) {
numGrade -= 0.3;
} else if (grade.endsWith("+")) {
numGrade += 0.3;
}
if (grade.equals("F+")) {
System.out.println("Not a valid input.");
}
if (grade.equals("F-")) {
System.out.println("Not a valid input.");
}
return numGrade;
}