【发布时间】:2020-08-05 18:05:19
【问题描述】:
每当我尝试运行时,我的错误就是“hmap.put(id, b0);”我做得对吗?我正在尝试进行用户输入并将其插入哈希图中。 它说: 没有找到适合 put(Integer,Student) 的方法 方法 Map.put(Integer,String) 不适用 (参数不匹配;学生不能转换为字符串) 方法 AbstractMap.put(Integer,String) 不适用 (参数不匹配;学生不能转换为字符串) 方法 HashMap.put(Integer,String) 不适用
(参数不匹配;Student 无法转换为字符串)
package javaapplication30;
import java.util.*;
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
class Student {
int id;
String sn, cor;
public Student(int id, String sn, String cor) {
this.id = id;
this.sn = sn;
this.cor = cor;
}
}
public class JavaApplication30 {
public static void main(String[] args) {
HashMap < Integer, String > hmap = new HashMap < Integer, String > ();
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 2; i++) {
System.out.print("id: ");
Integer id = sc.nextInt();
System.out.print("name: ");
String sn = sc.next();
System.out.print("course: ");
String cor = sc.next();
Student b0 = new Student(id, sn, cor);
hmap.put(id, b0);
}
for (Map.Entry m: hmap.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
}
【问题讨论】:
-
b0的类型为Student,但应为String或使用HashMap < Integer, Student > -
@Pavneet_Singh 非常感谢!我忘记了那一部分,现在我可以修复它了!非常感谢!