【发布时间】:2017-02-10 06:47:50
【问题描述】:
抱歉,问题稍微改了一下。
基本上我想知道aString 是否包含String。我的问题是当比较 aS aString) "aS".contains("String") 的子字符串时显示为真。
String a="st", b="string";
我跑了System.out.println(a.contains(b));
正如预期的那样,返回了false。我对包含有所了解,我一定是遗漏了其他东西。
所以看起来我的程序运行正常,但我做了一些调整然后回来,整个事情就停止了。我找出了常见的罪魁祸首(brackets, file io, etc.)。我发现if(string.contains(string)) 会不断运行,即:总是正确的。不知道为什么会这样,可能是我在代码中遗漏了一些东西。
这是我的输出示例(只是逐字符读取文件):
I
n
t
e
g
e
r
G
;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class comp{
public static void main(String[] args){
ArrayList<String> lines = new ArrayList<String>();
ArrayList<String> symbolTable = new ArrayList<String>();
ArrayList<String> parsedFile = new ArrayList<String>();
try {
File file = new File("symbolTable.txt");
Scanner scanner=new Scanner(file);
while (scanner.hasNextLine()&&symbolTable.add(scanner.nextLine().replaceAll("\\s+","").toLowerCase()));
scanner.close();
} catch (Exception ex) {
ex.printStackTrace();
}
try {
File file = new File("APU_CS400_input.txt");
Scanner scanner=new Scanner(file);
while (scanner.hasNextLine()&&lines.add(scanner.nextLine().replaceAll("\\s+","").toLowerCase()));
scanner.close();
} catch (Exception ex) {
ex.printStackTrace();
}
//runs through line by line of the input file
for(String line: lines){
String sBuild = "";
StringBuilder identifier = new StringBuilder("");
//moves through the line char by char
for(int i=0;line.length()>i; i++){
sBuild+=line.charAt(i);
//moves through the symbol table comparing each symbol to each string
//that is built char by char
for(String symbol: symbolTable){
//if the char string matches the symbol then any identifiers are saved and
//symbols are saved, the string is then reset to empty
//This is where i seem to get an issue
***if(sBuild.contains(symbol)){***
if(symbol.length()<sBuild.length()){
identifier.append(sBuild,0,sBuild.length()-symbol.length());
parsedFile.add(identifier.toString());
identifier.delete(0,sBuild.length()-symbol.length());
}
sBuild="";
parsedFile.add(symbol);
}
}
}
}
for(String symbol:parsedFile){
System.out.println(symbol);
}
}
}
Blockquote
【问题讨论】:
-
为什么不是真的?
-
确实,它总是应该是真的。
-
“抱歉,稍微改变了问题”——这是一个错字,应该写成“抱歉,把问题彻底改成了完全不同的东西”。
-
如果
sBuild.contains(symbol)在您认为应该为 false 时返回 true,则可能sBuild和/或symbol不是您认为的值。这就是 debugging 用于找出问题所在的地方。 你应该试试!