我在這段代碼中遇到問題,我試圖在編譯器過程中爲我的項目構建一個掃描器,掃描器從用戶處獲取任何輸入並將其分離爲令牌。將是:打印每個令牌和它的類型(如:號碼,標識符,關鍵字,加號等),最後打印令牌的數量。如何用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);
}
}
樣本輸入,預期輸出和實際輸出將會有所幫助。 –