0
votes
<%@ page import="java.util.Map;" %>
<%@ page import ="java.util.Hashtable;" %>
<%@ page import ="java.util.HashMap;" %>

<%
    int i,val;
    val=0;
    i=1;    
    String word = "abcdefghijklmnopqrstuvwxyz";
    Map dictionary = new HashMap();
    for(i=0;i<25;i++) {
        dictionary.put(word.charAt(i), val + 1)      
    }   
    for(String key: dictionary.keySet())
        out.println(key + ": " + dictionary.get(key));    
%>

I got this error

org.apache.jasper.JasperException: PWC6033: Error in Javac compilation for JSP

PWC6197: An error occurred at line: 5 in the jsp file: /quiz1/test.jsp PWC6199: Generated servlet error: incompatible types required: java.lang.String found: java.lang.Object

PWC6199: Generated servlet error: /test_jsp.java uses unchecked or unsafe operations.

PWC6199: Generated servlet error: Recompile with -Xlint:unchecked for details.

1
word.charAt(i) return a char. So your key in the map is a char not a String. You should declare your Map with generics Map<String,Integer> dictionary = new HashMap<String,Integer>()Jens
@Jens or Map<Character, Integer>.Luiggi Mendoza

1 Answers

1
votes

Semicolon is not allowed in import page directive as shown below instead use comma to import multiple package in the same page import.

<%@ page import="java.util.Map;" %>

I suggest you to use JavaServer Pages Standard Tag Library instead of Scriplet.

Sample code that produces the same result:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<jsp:useBean id="dictionary" class="java.util.Hashtable" />
<c:set var="word" value="abcdefghijklmnopqrstuvwxyz" />

<c:forEach begin="0" end="25" var="index">
    <c:set target="${dictionary}"
        property="${fn:substring(word, index,index+1)}" value="${index+1}" />
</c:forEach>

<c:forEach var="entry" items="${dictionary}">
    ${entry.key} : ${entry.value}<br>
</c:forEach>

Read more about the other JSTL tags and find more tutorials here on JSP - Standard Tag Library


Try with

for (Object key : dictionary.keySet())

instead of

for (String key : dictionary.keySet())

that will solve the problem because Map with raw type returns keys of Object type but I never suggest you to use raw type instead make it generic.