【问题标题】:Printing variables of type int excluding functions打印 int 类型的变量,不包括函数
【发布时间】:2016-04-01 07:12:59
【问题描述】:

我正在编写一个程序,它从文件中逐行读取代码,并打印“int”之后的任何内容。

例如:

int x;
int y;

打印出来:

x
y

这是我目前写的代码

BufferedReader br = new BufferedReader(new FileReader("C:\\example.txt"));

String line = null;
while((line = br.readLine()) != null)
{
    StringTokenizer token = new StringTokenizer(line);

    while(token.hasMoreTokens())
    {
        String s = null;
        s = token.nextToken();

        if(s.equals("int"))
        {
            System.out.println(token.nextToken());
        }
    }
}

但是,我想排除要打印的 int 类型的函数,例如本例中的“MyFunction”

x 
z
MyFunction(int
y)
x,
y

输入文件:

int x = 137;
int z = 42;
int MyFunction(int x, int y) {
   printf("%d,%d,%d\n", x, y, z);
   {
      int x, z;
      z = y;
      x = z;
      {
        int y = x;
        {
          printf("%d,%d,%d\n", x, y, z);
        }
        printf("%d,%d,%d\n", x, y, z);
      }
      printf("%d,%d,%d\n", x, y, z);
    }
 }

我是java新手,请耐心等待。

【问题讨论】:

  • 提供完整的输入文件可能会有所帮助

标签: java token tokenize


【解决方案1】:

试试这个。仅适用于与上述类似的输入。

while((line = br.readLine()) != null)
{
   StringTokenizer token = new StringTokenizer(line);

   while(token.hasMoreTokens())
   {
     String s = null;
     String r = null;
     s = token.nextToken();

     if(token.hasMoreTokens()){  //if s was not last token get next one
        r = token.nextToken();
    }
    if(s.equals("int") && r != null && r.length()<3) 
    {
        System.out.println(r.substring(0, 1)); // just to print x instead of x,
    }
}

}

【讨论】:

  • 这将起作用,但仅适用于名称为一个字符长的变量。如果你有像int a( int x, int y) 这样的方法,它会失败(注意第一个参数前的空格)。一个改进是不检查r 的长度,而是检查它是否后跟((使用正则表达式)并仅在它是逗号时删除最后一个字符
  • 您的代码绝对是对我的改进,但如果我还想在 MyFunction 参数中打印 x 和 y 怎么办?在第 6 行“int x, z;”我还想打印出 z,因为它也被声明为 int。
【解决方案2】:

你也可以试试这个。

while((line = br.readLine()) != null){
        String cleaned = line.trim(); //remove leading and trailing white space 
        String [] parts = cleaned.split(" |\\(");// split using white space or opening brace            
        if (line.matches("(\\s*)int(\\s*)(\\w+)(,\\s*\\w+)*(;)")){ // check for multiple variable declariation e.g. int a,b,c;
            for (int k = 1; k <parts.length; k++){
                System.out.println(parts[k]);                            
            }
        }
        else {
            for (int i = 0; i <parts.length-1; i=i+2){
                if((parts[i].equals("int")&&parts[i+1].length()<3) ){ //requires variable name length to be one
                    System.out.println(parts[i+1].substring(0, 1));
                }                            
            }                       
        }                
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 2020-02-11
    • 2016-08-10
    • 1970-01-01
    • 2021-04-06
    相关资源
    最近更新 更多