0
public class Md2html {
    public static void main(String[] args) throws IOException {

       String stringToConvert = new Scanner(System.in).nextLine();
       System.out.println(convert(stringToConvert));

    }

    public static String convert(String str) {

         if (str.equals("# "))
             System.out.println(" ");

         Pattern pattern = Pattern.compile("(#+[^#]+)");
         Matcher matcher = pattern.matcher(str);

         while (matcher.find()) {
             String str1 = matcher.group(1);
             if(str1.replaceFirst("#+", "").length() == 0 ||
                str1.replaceFirst("#+", "").matches("[\\s]+")) 
                      continue;
             int n = str1.length() - str1.replaceFirst("#+", "").length();
             System.out.println("<h" + n + ">" + str1.substring(n) + 
                                "</h" + n + ">");

             double carac;
             carac = str.charAt(0);
             if(carac>65 & carac <=90) {
                  System.out.print("<p>");
                  System.out.println(str);
                  System.out.println("<p>");
             }
        }

        return ("");
    }     
}

Ok, so now I have an algorithm that converts # to < h1> < h2> depending on the number of #...I'm now trying to add < p> at the beginning of a paragraph and < /p> at the end of it. For some reason,the second part of the converter, which is supposed to add < p> at the beginning and < /p> at the end of a paragraph doesnt seem to work (it's the code starting with double carac). Can someone tell me what I'm doing wrong???

4

1 回答 1

0

You are printing two opening tags for a paragraph if the string starts with an uppercase letter and no closing tag. Replace

System.out.print("<p>");
System.out.println(str);
System.out.println("<p>");

with

System.out.print("<p>");
System.out.println(str);
System.out.println("</p>"); //<--here

Also, you should use a logical AND && instead of a bitwise AND & for boolean operations.

Also, String#charAt(int) returns a char, not a double. You are declaring carac as a double. Declare as a char instead.

于 2012-10-25T05:14:21.980 回答