下面的代码是迄今为止的整个程序(只是为了避免任何遗漏的部分。
我遇到的问题是我正在尝试使用 .substring(int,int) 方法从给定字符串中提取两个字符并将这两个字符写入一个单独的数组中。问题是使用 .substring() 从字符串中提取的每个字符都是空格。根本没有拉出任何字母。我使用简单的打印方法测试了该函数,结果显示打印 sentences.get(i).substring(j,j++)
仅打印空格。它用这些空白空间填充我的数组。
有什么线索可以解释是什么原因造成的吗?我的编译器没有给我任何错误或警告。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JacSim {
public static void main(String [] args) throws FileNotFoundException {
Scanner userScanner = new Scanner(System.in);
System.out.println("Please enter the filename for your input file (with extension).");
String fileName = userScanner.nextLine();
File file = new File(fileName);
Scanner scanner = new Scanner( new FileInputStream(file));
List<String> sentences = new ArrayList();
while (scanner.hasNextLine()) {
String sentence = scanner.nextLine();
sentences.add(sentence);
}
System.out.println("Input Sentences:\n");
for(int i=0;i<sentences.size();i++) {
System.out.println(i + " : " + sentences.get(i));
}
List<List<String>> shingles = new ArrayList();
sentences.stream().forEach((String _item) -> {
shingles.add(new ArrayList());
});
System.out.println("\nSorted Shingle Arrays:\n");
shinglesMethod(shingles, sentences);
}
private static List shinglesMethod(List<List<String>> shingles, List<String> sentences) {
for (int i=0;i<sentences.size();i++) {
for(int j=0;j++<sentences.get(i).length();j++) {
shingles.get(i).add(sentences.get(i).substring(j,j++));
}
showList( i, shingles.get(i) );
}
return shingles;
}
private static void showList( int n, List List ) {
System.out.print(n + " : ");
List.stream().forEach((o) -> {
System.out.print( o + " " );
});
System.out.println();
}
需要注意的代码块是
for (int i=0;i<sentences.size();i++) {
for(int j=0;j++<sentences.get(i).length();j++) {
shingles.get(i).add(sentences.get(i).substring(j,j++));
}
showList( i, shingles.get(i) );
}
忘记澄清扫描仪正在正确读取单词并且每个字符串都按预期读取。我发现的唯一问题是 .substring() 方法。
最佳答案
这似乎源于对 ++
的混淆。做。 j++
返回值j
以及之后增量j
.
.substring(j,j++)
将始终返回空字符串,因为它会递增 j
获取包含 j 和不包含 j 之间的子字符串后。 substring(j, j + 1)
可能会更符合您的需求。
您还需要使用j + 1 < sentences.get(i).length()
,而不是 j++
,因为您正在更改 j
的值当您尝试检查它时,这几乎肯定不是您想要的。唯一的地方j++
需要提到的是for循环中的update语句。
关于java - String.substring(i,j) 方法获取空格而不是实际字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28640317/