当我运行我的代码时,输出是这样的:
4 went down to the market
0 where she bought herself
1
0 kitten
0 she thought the
6 was
0 precious,
2 she
0 named the kitten
String index out of range: -1
但是期望的输出应该是这样的:
0 Lisa went down to the market
3 where she bought herself
0 a
1 kitten
2 she thought the
0 kitten was
5 precious,
0 so she
2 named the kitten
0 Princess
我收到了一个包含文本行的文本文件http://pastebin.com/h51eh8EX。我必须编写一个读取文本的类,计算每行开头的空格数,然后写入行以删除每行开头的空格,并用存在的空白数替换它们。 / p>
你能解释一下我的问题吗?
以下是代码:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Squeeze {
String fname;//name of the file that contains text to be squeezed
/**
* Constructor to initialize fname
* @param name - name of the file to be squeezed
*/
public Squeeze(String name)
{
//TODO Your code goes here
fname = name;
}
/**
* Method to remove and count any extra
* leading spaces
*
*/
public void squeezeText()
{
//TODO Your code goes here
try
{
File file = new File("squeeze.txt");
Scanner in = new Scanner(file);
while (in.hasNext())
{
String line = in.nextLine();
int count = line.substring(0, line.indexOf(" ")).length();
line = count + line.substring(line.indexOf(" "));
System.out.println(line);
}
in.close();
}
catch(Exception e)
{
System.out.println( "Error: " + e.getMessage());
}
}
}
答案 0 :(得分:0)
使用indexOf()对此不准确,因为它只会让您第一次出现空格字符。
Java String API:http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
答案 1 :(得分:0)
您的计数方法已关闭,最简单的方法就是循环遍历字符。这是你可以做到的一种方式 -
while (in.hasNext()) {
String line = in.nextLine();
int count = 0;
for (char c : line.toCharArray()) {
if (c == ' ') {
count++;
}
}
line = count + " " + line;
System.out.println(line);
}
答案 2 :(得分:0)
尝试使用正则表达式
while (in.hasNext())
{
String line = in.nextLine();
Pattern p = Pattern.compile("^\\s+\\w");
Matcher m = p.matcher(line);
if (m.find()) {
System.out.println(m.group().length() - 1 + " " + line);
} else {
System.out.println("0" + " " + line);
}
}