I don't know how to fix this. I want to intake a certain number of strings with a hashmap. I am still a beginner coder and just learned hashmap. PLS help.
public class Hashmap {
public static void main(String[] args) {
Scanner Scanner = new Scanner(System.in);
int lines = Scanner.nextInt();
Map<Integer, Integer> hash = new HashMap<Integer, Integer>();
for (int i = 0; i < lines; i++) {
hash.put(i, Scanner.next());
}
}
}
Scanner.next
returns a String
object. You cannot put a String
as the value in a map you declared as taking Integer
objects for values. Square peg, round hole.
You have a choice of three ways to fix.
You could change your map declaration to take String
objects as the value. Change this:
Map< Integer , Integer > map = new HashMap<>();
… to:
Map< Integer , String > map = new HashMap<>();
Or, you can collect integers from the Scanner rather than text. Call Scanner#nextInt
.
Or, you can collect text from the scanner, and then transform that text to an integer. Call Integer.valueOf
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.