我正在尝试编写一个用于在Java中操作符号表的程序。我使用链表数据结构作为表示我的符号表的方法;链表(单独)有一个键,与该键相关的值,以及指向下一个点的指针。链表还向用户提供将新节点插入列表的功能。似乎我对链表类的实现进展顺利,但是当我尝试编写一个主程序来测试时,我遇到了一些问题。尽管我以某种方式管理错误以处理异常,但我的代码中存在逻辑错误。这是我编写的代码段和输出:
import java.util.Scanner;
public class Test_GPA {
public static void main(String[]args){
// create symbol table of grades and values
GPA<String, Double> grades = new GPA<String, Double>();
grades.put("A", 4.00);
grades.put("B", 3.00);
grades.put("C", 2.00);
grades.put("D", 1.00);
grades.put("F", 0.00);
grades.put("A+", 4.33);
grades.put("B+", 3.33);
grades.put("C+", 2.33);
grades.put("A-", 3.67);
grades.put("B-", 2.67);
Scanner input = new Scanner(System.in);
double numb =0; int i=0;
double sum = 0.0;
String grade;
Double value;
System.out.println("Please enter number of courses:");
numb=input.nextInt();
while(i<numb){
System.out.println("Please enter the grade for course"+(i+1)+":");
grade = input.nextLine();
value = grades.get(grade);
try{
sum += Double.valueOf(value);
}catch(Exception e){}
i++;
}
double gpa = sum/numb;
System.out.println("GPA = "+gpa);
问题是代码总是跳过用户对第一个条目的读取。例如,如果我运行此程序并输入课程数为4,结果将如下所示:
Please enter number of courses:
4
Please enter the grade for course1:
Please enter the grade for course2:
A
Please enter the grade for course3:
A
Please enter the grade for course4:
A
GPA = 3.0
我实际上不知道我犯的错误在哪里。当然,错过了导致GPA错误计算的第一个条目的读数。拜托,是否有人有兴趣向我展示如何修复错误。我已经尝试了几乎所有我知道的东西,它仍然无效。仅供参考,这是我第一次用Java编程。提前谢谢。
答案 0 :(得分:1)
首先,LinkedList
的实现不正确linklist不是数据结构的键值类型,它只是将元素链接到其他元素。我建议你研究一下这种用法更好的HashTable
。您的代码中发生的事情是,当您使用nextInt()
输入时,新行字符不会被消耗掉。下面的代码应该做的诀窍
numb = Integer.parseInt(input.nextLine());