我正在尝试制作一种可以检测Java语法并突出显示该代码的系统。但是,我似乎在查找字符串中的字符串时遇到麻烦。
这是我到目前为止所拥有的:
import java.util.Scanner;
public class Client {
private static String[] javaKeywords = {
"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue",
"default", "do", "double", "else", "enum", "extends", "final", "finnaly", "float", "for", "goto", "if",
"implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "primitve",
"private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized",
"this", "throw", "throws", "transient", "try", "void", "volatile", "while"
};
private static String[] javaSyntax = {
"++", "--", "~", "!", "*", "/", "%", "+", "-", " <<", ">>", ">>>", "<", ">", "<=", ">=", "==", "!=", "&",
"^", "|", "&&", "||", "?", ":", "=", "+=", "-=", "/=", "%=", "&=", "^=", "|=", "<<=", ">>=", ">>>="
};
private static Scanner scanner = new Scanner(System.in);
private static StringBuilder builder = new StringBuilder();
public static void main(String args[]) {
String input;
while(!(input = scanner.nextLine()).toLowerCase().contains("exit")) {
switch(input.toLowerCase()) {
case "print":
System.out.println(builder.toString());
continue;
case "clear":
builder = new StringBuilder();
continue;
}
builder.append(input + "\n");
codeWrap(builder.toString());
}
}
private static void codeWrap(String code) {
int A4I = 0, position; // A4I = Account for insert length
for(String keyword: javaKeywords) {
if((position = findInString(code, keyword)) != -1) {
builder.insert(position + A4I, "[code]");
A4I += 6;
builder.insert(position + keyword.length() + A4I, "[/code]");
A4I += 7;
}
}
}
private static int findInString(String string, String keyword) {
for(int index = 0, keywordIndex = 0; index < string.length(); index++) {
keywordIndex = (string.charAt(index) == keyword.charAt(keywordIndex)) ? ++keywordIndex : 0;
if(keywordIndex == keyword.length()) return ((index + 1) - keyword.length());
}
return -1;
}
}
这在大多数情况下都有效,但是,如果您尝试用两个关键字包装一个句子,则如果关键字b在javaKeywords数组中的关键字a之前,它将返回一个奇怪的结果。
例如:在b(while)之前有a(抽象)的结果
abstract while
print
[code]abstract[/code] [code]while[/code]
b(while)在a(abstract)之前的结果
while abstract
print
while [code]a[code]bstra[/code]ct[/code]
你A4I
不需要在这种情况下变量,并导致你做出那些已经计算偏移。请注意以下几点:
while abstract
>loop finds 'abstract' at position 6
while [code]abstract[/code]
>A4I is now making all offsets +13
>loop finds 'while' found at position 0
>you add that +13 offset to the insert making it drop right in the middle of the abstract
您还将向codeWrap
方法中传递2个字符串,因为字符串是不可更改的,因此您要在字符串中搜索索引,然后在其他字符串上使用它。您还会在程序中发现其他一些奇怪的问题,但这应该可以解决您的直接问题
private static void codeWrap() {
int position;
for(String keyword: javaKeywords) {
if((position = findInString(builder.toString(), keyword)) != -1) {
builder.insert(position, "[code]");
builder.insert(position + keyword.length()+6, "[/code]");
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句