我在这段代码中遇到问题,我试图在编译器过程中为我的项目构建一个扫描器,扫描器从用户处获取任何输入并将其分离为令牌。将是:打印每个令牌和它的类型(如:号码,标识符,关键字,加号等),最后打印令牌的数量。如何用stringtokenizer生成扫描器
我试图多个输入端,并且每个时间输出是标识符,并且当我试图输入一个号码或关键字或+或 - 的输出是标识..
这是我的代码:
import java.util.Scanner;
import java.util.StringTokenizer;
public class MyScanner
{
public static void main(String[] args)
{
String reserved_Keywords[] = { "abstract", "assert", "boolean",
"break", "byte", "case", "catch", "char", "class", "const",
"continue", "default", "do", "double", "else", "extends", "false",
"final", "finally", "float", "for", "goto", "if", "implements",
"import", "instanceof", "int", "interface", "long", "native",
"new", "null", "package", "private", "protected", "public",
"return", "short", "static", "strictfp", "super", "switch",
"synchronized", "this", "throw", "throws", "transient", "true",
"try", "void", "volatile", "while" };
Scanner sc = new Scanner(System.in);
System.out.println("Enter Your Text: ");
String str = sc.nextLine();
StringTokenizer st = new StringTokenizer(str);
int numofTokens = st.countTokens();
while(st.hasMoreElements())
{
for (int i = 0; i < reserved_Keywords.length; i++)
{
if (st.equals(reserved_Keywords[i]))
{
System.out.print(st.nextElement() + "\t");
System.out.println("Is Reserved Keyword");
}
}
if (st.equals("+"))
{
System.out.print(st.nextElement() + "\t");
System.out.println("Is Plus Sign");
}
else if (st.equals("-"))
{
System.out.print(st.nextElement() + "\t");
System.out.println("Is Minus Sign");
}
else if (st.equals("*"))
{
System.out.print(st.nextElement() + "\t");
System.out.println("Is Multiply Sign");
}
else if(st.equals("/"))
{
System.out.print(st.nextElement() + "\t");
System.out.println("Is Divide Sign");
}
else if (st.equals("="))
{
System.out.print(st.nextElement() + "\t");
System.out.println("Is Assignment Operator");
}
else
{
System.out.print(st.nextElement() + "\t");
System.out.println("Is Identifier");
}
}
sc.close();
System.out.println("Number of Tokens = " + numofTokens);
}
}
样本输入,预期输出和实际输出将会有所帮助。 –