我正在尝试获取用户输入并将其分配给不同类中的 HashMap 。我的意图是在主类中声明一个映射并将值存储在该映射中,然后通过构造函数将主类映射中收集的数据分配给另一个类中的映射。 map 结构<string, integer>
目标是打印两个值而不是仅打印一个值。我该怎么办?到目前为止,我在将值放入 map (oldVal)时遇到了这个特定错误
Error: required: java.lang.string found: java.lang.integer
这是我的代码:
主类 -
import java.util.HashMap;
import java.util.Scanner;
import java.util.Random;
public class Main{
public static void main(String[] args) throws Exception{
int choice;
final int MAX = 999999999;
boolean loopAgain = true;
HashMap<String, Integer> mapRatings = new HashMap<>();
System.out.println("Enter movie rating (PG OR NC): ");
String rating = input.nextLine();
System.out.println("Enter the rating age (13 OR 17): ");
Integer ratingId = Integer.parseInt(input.nextLine());
String oldVal = mapRatings.put(rating, ratingId);
}
}
电影类:
import java.util.*;
public class Movie {
private String id;
private String name;
private String description;
private String[] genre;
private String[] actors;
private String[] language;
private String countryOfOrigin;
private Map<String, Integer> ratings;
//Constructor
public Movie(String id, String name, String description, String[] genre, String[] actors, String[] language, String countryOfOrigin, Map<String, Integer> ratings){
this.id = id;
this.name = name;
this.description = description;
this.genre = genre;
this.actors = actors;
this.language = language;
this.countryOfOrigin = countryOfOrigin;
this.ratings = ratings;
}
public void setRatings(Map<String, Integer> ratings){
this.ratings = ratings;
}
}
最佳答案
检查Map documentation如下:
V put(K key, V value)
参数:
key - key with which the specified value is to be associated
value - value to be associated with the specified key
即返回类型应与值
的类型匹配。在您的情况下,您的值是 int
类型,因此您应该编写
int oldVal = mapRatings.put(rating, ratingId);
关于java - 获取用户输入并将其分配给不同类中的 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60691537/