java - 获取用户输入并将其分配给不同类中的 HashMap

标签 java

我正在尝试获取用户输入并将其分配给不同类中的 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/

相关文章:

Java 12 intellij 开关表达式不起作用

java - hadoop在reducer中获取最大值

java - 放心一点: Fail to convert a response to an array of objectsRe

java - 当组合框未唯一标识时,如何将组合框值设置为数组值?

java - 如何创建匹配给定字符集的模式?

java - 登录成功后,url重新重定向到/login

java - java中字节范围如何为-128到127。这怎么可能?

java - 我有一个 GreetingServer.java (使用套接字)。想为它制作一个JFrame

java - 了解 Spring 3.0 示例中的 Ajax 简化

java - 用于 Java Web 应用程序的可嵌入消息传递组件