单独的字符串输入从文本文件java

时间:2013-08-08 09:50:37

标签: java arrays

我是一名java初学者,我对从文本文件中扫描有一个小问题 假设我有一个像这样的文本文件

abc
012
4g5
(0 0 0)
(0 1 3)
(1 2 6)
(1 1 0)
abcde
blahblah

现在我想只为括号内的字符串创建一个数组,这意味着如何告诉扫描器只扫描从第一个打开的括号开始的字符串,在下面的右括号后重置数组输入,并最终停止最后一个右括号后扫描。这就是我到目前为止所做的:

*对于数组,它将第一个数字作为行#,第二个数字作为col#,第三个数字作为值

while (file.hasNext()) {
    if (file.next().equals("(")) {
        do {
            2Darray[Integer.parseInt(file.next())][Integer.parseInt(file.next())] = file.next(); 

        }
        while (!file.next().equals(")"));
}

感谢

1 个答案:

答案 0 :(得分:3)

我建议您使用RegEx来匹配您的参数。

不得不提及以下情况中的文件BufferedReaderDocument yourself on that

while ((line = file.readLine()) != null)
{
    if( line.matches("\\((.*?)\\)") ) // Match string between two parantheses  
    {
         String trimmedLine = line.subString(1, line.length - 1); // Takes the string without parantheses
         String[] result = trimmedLine.split(" "); // Split at white space   
    }
}

// result[0] is row#
// result[1] is col#
// result[2] is value

此代码中的一个缺陷是,您必须尊重您在问题中提到的文字行格式(例如"(3 5 6)")。

相关问题