这是我的代码
import java.io.File;
import java.util.Scanner;
class keyword {
String a[] = { "where", "while", "if", "switch","int","char","else"};
}
class jiefu {
String c[] = { ",", ".", "/" ,"(",")","{","}"};
}
class yunsuanfu {
String a[] = { "+", "-", "*", "/" };
}
public class crystal {
public static void main(String[] args) {
String a = "";
String c="";
try {
File file = new File("d://新建文本文档.txt");
Scanner sc = new Scanner(file);
while(sc.hasNext()) {
a += sc.next();
}
c=a.trim();
} catch (Exception e) {
System.out.println("there is something wrong");
}
charge(c);
}
static void charge(String a) {
String c = "";
String x = "";
String ni="";
int i = 0;
keyword test = new keyword();
int h = test.a.length;
jiefu jf = new jiefu();
yunsuanfu ysf = new yunsuanfu();
int length = a.length();
char p[] = new char[length + 1];
for (i = 0; i < length; i++) {
if((p[i]!='\r')&&(p[i]!='\n'))
p[i] = a.charAt(i);
}
for(i=0;i<length;i++)
{
while((Character.isLetter(p[i]) == true)
|| (Character.isDigit(p[i]) == true)&&(p[i]!=' ')&&(p[i]!='\r')&&(p[i]!='\n'))
{
c += p[i];
ni +=p[i];
i++;
for (int j = 0; j < h; j++)
{
if (c.equals(test.a[j]))
{
ni=ni.replaceAll(test.a[j], "");
System.out.println("关键字" +test.a[j]);
}
}
}
if(ni!="\n"){
System.out.println("标示符" +ni);}
ni="";
c="";
}
i = 0;
while((i<length)&&(Character.isDigit(p[i])))
{
x += p[i];
i++;
}
if (x != "") {
System.out.println("常数:" + x);
}
length = jf.c.length;
for (i = 0; i < length; i++) {
if (a.indexOf(jf.c[i]) != -1) {
System.out.println("界符" + jf.c[i]);
}
}
length = ysf.a.length;
for (i = 0; i < length; i++) {
if (a.indexOf(ysf.a[i]) != -1) {
System.out.println("运算符" + ysf.a[i]);
}
}
}
}
分析的代码是while(a>b)
{
if m>=x
a=a+1 ;
else
while (k=h2)
x=x+2 ;
m=n+x*(m+y);
}
但是结果是
关键字while
标示符
标示符a
标示符b
标示符
关键字if
标示符m
标示符
标示符xa
标示符a
标示符1
关键字else
标示符while
标示符k
标示符h2
标示符x
标示符x
标示符2
标示符m
标示符n
标示符x
标示符
标示符m
标示符y
标示符
标示符
界符(
界符)
界符{
界符}
运算符+
运算符*
中间的那些空格应该怎么消除啊,大神帮帮忙吧
------解决方案--------------------
replaceAll方法有用呀,就是把你的关键字替换成空字符串
消去空格的方法为在: 将if(ni!="\n"){System.out.println("标示符" +ni);}替换成
if (!ni.trim().equals("")){System.out.println("标示符" + ni);}
不过程序有个漏洞..标示符xa这个结果有点....