我正在制作一个程序,要求5名学生输入他们的名字和gpa,这将计算最低和最高gpa,以及平均值。我继续得到"不兼容的类型"错误,即使我已经在构造函数中初始化了变量。
System.out.println("Please enter the gpa for the second student");
gpa2 = scan.nextDouble();
System.out.println("Please enter the name for the third student");
student3 = scan.nextLine();
System.out.println("Please enter the gpa for the third student");
gpa3 = scan.nextDouble();
System.out.println("Please enter the name for the fourth student");
student4 = scan.nextLine();
System.out.println("Please enter the gpa for the fourth student");
gpa4 = scan.nextDouble();
System.out.println("Please enter the name for the last student");
student5 = scan.nextLine();
System.out.println("Please enter the gpa for the last student");
gpa5 = scan.nextDouble();
//use scanner to get the gpa
System.out.println("Student Name /" + " Student GPA");
System.out.println("----------------------------);
System.out.println(student1 +" / "+ gpa1);
System.out.println(student2 +" / "+ gpa2);
System.out.println(student3 +" / "+ gpa3);
System.out.println(student4 +" / "+ gpa4);
System.out.println(student5 +" / "+ gpa5);
/**
* Creates objScore object and passas in student parameters to class StudentScore...name and GPA scores
*/
StudentScore objScore = new StudentScore(student1, gpa1, student2, gpa2, student3, gpa3, student4, gpa4, student5, gpa5);
找到1个错误:
文件: C:\ Users \ Mikey Espinal \ OneDrive \ Documents \ StudentScoreTester.java [line:46]
错误:不兼容的类型:double无法转换为java.lang.String
答案 0 :(得分:3)
您应该使用String.valueOf(gpa1)
代替gpa1
。这会将您的double
转换为String
。与其他double
(gpa2
,gpa3
,...)相同的需要。
答案 1 :(得分:2)
我认为你的问题是你的代码在每次scan.nextDouble()之后都没有调用scan.nextLine()。
答案 2 :(得分:2)
您的代码没有问题。请检查StudentScore课程的构造函数。我确定你已经使用String到处而不是所有gpa值的double。 Sol 1:如上所述,通过Andrew String.valueOf(gpa1)将gpa转换为String,然后传递给构造函数或者 Sol2:更改构造函数并在所有gpa位置使用Double / double。
答案 3 :(得分:2)
我只能猜测您将gpaX
变量声明为String
类型。将它们声明为double
类型 - 这样,您将它们存储为double
,直到它们被转换为字符串以进行打印。
答案 4 :(得分:2)
在打印与java不兼容的行时,您正在使用double值连接字符串。 您需要做的就是将double类型转换为String。这可以使用 String.valueOf()函数来完成。 尝试: System.out.println(student1 +“/”+ String.valueOf(gpa1);