如果此“//”,则跳过当前行。发现了扫描仪 [英] Skip current line if this "//" found Scanner

查看:68
本文介绍了如果此“//”,则跳过当前行。发现了扫描仪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作词法分析器并且我在处理评论时遇到困难。



如果文件中出现//,我实际上正在尝试处理.txt然后该行应该被忽略并且循环必须移动到下一行以获得更多标记,实际上我正在从文件中读取单词并且如果出现空格,那么该单词应该单独存储在arraylist中以便稍后我可以比较关键字标识符等。



以下是代码:

I'm making Lexical Analyzer and i got stuck in handling Comments .

I'm actually trying to handle that if "//" appears in the file.txt then that line should be ignored and loop must move to next line for more tokens , actually I'm reading the words from file and if white space occurs then that word should be separately stored in arraylist so that I can later compare the keywords with the identifiers etc.

Here is the code:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;



public class lex {



	public static void main(String[] args) throws FileNotFoundException {
	
		List<String> al = new ArrayList<String>();		
			
			FileReader fin = new FileReader("C:\\Users\\PHLAMBY\\Desktop\\file.txt");
			Scanner s = new Scanner(fin);		  
		    
			 s.useDelimiter(" ");
			 
			int lineNum;
		    String A ;
		    
		    for(lineNum=1;s.hasNextLine();lineNum++){
				
					 A=s.next();
				 if(!A.contains("//")){					
					 al.add(A);
				 }
				 else
					 break;
		    }
		  
		  
		  for(int i =0 ;i<al.size(); i++){
			 System.out.println(al.get(i));
		  }	 		    
	}}





这是文本文件:





This is the text file :

{ }* +- ==abstract

// extends testing etc etc



输出:

{

} *

+ -



现在,我没有得到正确的输出应该有最后一个关键字==抽象打印但它没有分离和打印和评论没有正确处理。



谢谢提前!


Output :
{
}*
+-

Now, I'm not getting proper output there should be last keyword "==abstract" print but it is not seperating and getting printed and comment is not properly handled.

Thanks in advance!

推荐答案

使用分隔符设置意味着不会将换行符视为标记分隔符。此外, break 语句终止循环,这可能不是您想要的。代码应该类似于:

Your use of the delimiter setting means that newlines will not be treated as token separators. Also the break statement terminates the loop, which may not be what you want. The code should be something like:
Scanner s = new Scanner(fin);
int lineNum;
String A ;
for(lineNum=1; s.hasNext(); lineNum++) {
    A=s.next();
    if(!A.contains("//")){
        al.add(A);
    }
    else {
        s.nextLine(); // skip comment lines
    }
}



如上所述,使用 nextLine 可确保循环继续到文件末尾。


Using nextLine, as above, ensures that the loop continues to the end of the file.


这篇关于如果此“//”,则跳过当前行。发现了扫描仪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆