Ruby字符串可以';不要被强迫去修理
我正在尝试创建一个程序,用于根据学生记录计算GPA。输入学生的姓和名后,我会发现以下错误:Ruby字符串可以';不要被强迫去修理,ruby,Ruby,我正在尝试创建一个程序,用于根据学生记录计算GPA。输入学生的姓和名后,我会发现以下错误: Please provide the last name of the desired student: Cirello Please provide the first name of the desired student: Brian proj3.rb:55:in `+': String can't be coerced into Fixnum (TypeError)
Please provide the last name of the desired student:
Cirello
Please provide the first name of the desired student:
Brian
proj3.rb:55:in `+': String can't be coerced into Fixnum (TypeError)
from proj3.rb:55:in `block in <main>'
from proj3.rb:53:in `each'
from proj3.rb:53:in `<main>'
请提供所需学生的姓氏:
西雷罗
请提供所需学生的名字:
布瑞恩
proj3.rb:55:in`+':无法将字符串强制转换为Fixnum(TypeError)
来自proj3.rb:55:in'block in'
来自proj3.rb:53:in'each'
from proj3.rb:53:in`'
请帮我解决这个问题。这是我的密码:
stud_id = []
last_name = []
first_name = []
course_number = []
course_name = []
prof_name = []
credit_hours = []
grade = []
grade_values = {
"A" => 4,
"B" => 3,
"C" => 2,
"D" => 1,
"F" => 0 }
fin = File.open("student-records.txt", "r")
while line = fin.gets
fields = line.chomp.split(',')
stud_id << fields[0]
last_name << fields[1]
first_name << fields[2]
course_number << fields[3]
course_name << fields[4]
prof_name << fields[5]
credit_hours << fields[6]
grade << fields[7]
end
fin.close
puts "Please provide the last name of the desired student:"
desired_last_name = gets.chomp
puts "Please provide the first name of the desired student:"
desired_first_name = gets.chomp
desired_student_credit_hours = 0
desired_student_grades = 0
desired_student_indexes = [7]
if last_name.include?(desired_last_name) && first_name.include?(desired_first_name)
last_name.each do |student_last_name, i|
if student_last_name == desired_last_name
desired_student_indexes << i
end
end
end
desired_student_indexes.each do |desired_student_index|
desired_student_grades += grade_values[grade[desired_student_index]]
desired_student_credit_hours += credit_hours[desired_student_index]
end
final_gpa = desired_student_grades / desired_student_credit_hours
puts "This student's final GPA is: #{final_gpa}"
stud_id=[]
姓氏=[]
first_name=[]
课程号=[]
课程名称=[]
教授姓名=[]
学分时数=[]
等级=[]
等级_值={
“A”=>4,
“B”=>3,
“C”=>2,
“D”=>1,
“F”=>0}
fin=File.open(“student records.txt”、“r”)
而line=fin.get
fields=line.chomp.split(',')
stud_id请检查将字符串转换为整数的to_i
方法。您需要将其附加到grade\u值[成绩[期望的学生索引]]
和credit\u小时[期望的学生索引]
中,如下所示:
desired_student_grades += grade_values[grade[desired_student_index]].to_i
desired_student_credit_hours += credit_hours[desired_student_index].to_i
thanx计算部分呢?当我输入名称时,它仍然给我一个错误?对不起,我不理解你的问题。什么错误?我的建议没有修复原始问题中报告的错误吗?@cooler请一次问一个问题。如果您现在有不同的问题,那么最好打开一个新问题来准确地解决您的新问题。您的数据结构有点混乱。考虑将每个学生存储在散列或结构对象中。