我在此代码中有问题,我正在尝试为我的项目中的项目构建扫描仪,扫描仪会从用户那里获取任何输入并将其分开为令牌。输出将是:打印每个令牌及其类型(例如:数字,标识符,关键字,符号...等),最后打印令牌的数量。
我尝试了更多的输入,并且每次输出是标识符,当我尝试输入一个数字或关键字或 或 - 输出为标识符时。
这是我的代码:
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);
}
}
您始终比较(call equals(..)(使用StringTokenizer,而不是StringTokenizer返回的令牌。
要提起它,添加时循环的第一行
String TOKEN = st.nextToken();
,然后用代币替换所有比较(调用equals())。
(您应该在上面的案例字母中命名变量,我只是为了可读性而这样做)
然后您的代码看起来像:
StringTokenizer st = new StringTokenizer(str);
int numofTokens = st.countTokens();
while( st.hasMoreElements() )
{
String TOKEN = st.nextToken();
for (int i = 0; i < reserved_Keywords.length; i++)
{
if ( TOKEN.equals(reserved_Keywords[i]) )
{
System.out.print(st.nextElement() + "t");
System.out.println("Is Reserved Keyword");
}
}
...