循环遍历 JAVA StringTokenizer

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16565850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:19:01  来源:igfitidea点击:

Loop through JAVA StringTokenizer

java

提问by Lonerli

please I need help badly. Thank You

请我急需帮助。谢谢

I read a text file from my hard disk which contains as follows....

我从我的硬盘中读取了一个文本文件,其中包含以下内容....

void main()
{

    int A = 5;
    int B = 5;
    int C ; 
    C = A + B;
    cout << C ; 

}

So, what I need to do is that.. Lets say I have an array of...

所以,我需要做的是......假设我有一个......

String []KeyWord = {"void", "main()"};
String []DataType = {"int", "float"};

So I want to loop through each token and check whether for example its a key word or a datatype. I used java netBeans and I code as follows

所以我想遍历每个标记并检查例如它是关键字还是数据类型。我使用了 java netBeans,我的代码如下

int k = 0; int l = 0;

StringTokenizer Tokens;

while ((CurrentLine = ReadFile.readLine()) != null)
{
    Tokens = new StringTokenizer(CurrentLine, " ", true);
    for (int i = 0; Tokens.hasMoreTokens(); i++)
    {
        if (Tokens.nextToken().contains(KeyWord[k]))
        {
            jTextArea1.append(KeyWord[k] + "\n");
            k++;
        } 
        else if (Tokens.nextToken().contains(DataType[l]))
        {
            jTextArea2.append(DataType[l] + "\n");
        }
    } 
} 

回答by Ravi Thapliyal

No, your code won't work. While you're iterating over the tokens you never increment k and l which remain 0through out; implying that you're always checking for the first keyword and data type only.

不,您的代码将不起作用。当您迭代令牌时,您永远不会增加 k 和 l ,它们始终保持不变0;这意味着您始终只检查第一个关键字和数据类型。

Recommendations

建议

  • Use the simpler String.split()instead of StringTokenizerwhich is generally used when you have more than one delimiters and a bit more advanced needs than just a basic split. And since you're passing returnDelimsas true(third parameter) you're receiving your spaces back as your tokens as well (which ins't what you want I suppose).

  • Use a HashSet<String>to store your keywords/datatypes instead of an Array or ArrayList. This would give you much better performance as compared to iterating the Array or using ArrayList.contains().

  • Sample Implementation

    HashSet<String> keyWords = new HashSet<String>(
            Arrays.asList(new String[] {"void", "main()"}));
    HashSet<String> dataTypes = new HashSet<String>(
            Arrays.asList(new String[] {"int", "float"}));
    
    String newLine = System.getProperty("line.separator");
    while ((currentLine = readFile.readLine()) != null) {
        String[] tokens= currentLine.split(" ");
        for (String token : tokens) {
            if (keyWords.contains(token)) {
                jTextArea1.append(token + newLine);
            } else if (dataTypes.contains(token)) {
                jTextArea2.append(token + newLine);
            }
        }
     }
    
  • 当您有多个分隔符和比基本拆分更高级的需求时,通常使用更简单的String.split()而不是StringTokenizer哪个。并且由于您returnDelims作为true(第三个参数)传递,因此您也将您的空格作为您的令牌接收(我想这不是您想要的)。

  • 使用 aHashSet<String>来存储您的关键字/数据类型,而不是 Array 或 ArrayList。与迭代 Array 或使用ArrayList.contains().

  • 示例实现

    HashSet<String> keyWords = new HashSet<String>(
            Arrays.asList(new String[] {"void", "main()"}));
    HashSet<String> dataTypes = new HashSet<String>(
            Arrays.asList(new String[] {"int", "float"}));
    
    String newLine = System.getProperty("line.separator");
    while ((currentLine = readFile.readLine()) != null) {
        String[] tokens= currentLine.split(" ");
        for (String token : tokens) {
            if (keyWords.contains(token)) {
                jTextArea1.append(token + newLine);
            } else if (dataTypes.contains(token)) {
                jTextArea2.append(token + newLine);
            }
        }
     }
    

回答by darijan

First, convert keyWordand dataTypearrays to ArrayList.

首先,转换keyWorddataType阵列ArrayList

Then, do something like:

然后,执行以下操作:

while ((currentLine = ReadFile.readLine()) != null) {
   String[] tokens= currentLine.split(" ");
   for (String token : tokens) {
      if (keyWord.contains(token)) {
         jTextArea.append(token);
      }
   } 
    //rest of the code is similar
}