對不起,稍微改變了這個問題。if(s1.Contains(s2))似乎永遠是真的
本質上我想知道如果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
爲什麼會不會是真的? – Zarwan
事實上,它總是**應該是真實的。 –
「對不起,稍微改變了這個問題」 - 這是一個錯字,它應該讀「對不起,將問題從根本上改變爲完全不同的東西」。 – ajb