我有以下代码,除了命令行参数外,其他代码都有效,每次我写时,"Insertion"
它都不会进入if语句,因此输出为"Algorithm not found. Use: [ Insertion | Merge ]"
public static void main(String[] args) throws IOException, InsertionAndMergeException, Exception {
if( args.length < 2 ) {
System.out.println("Use: <path> <algorithm> ");
System.exit(1);
}
if(args[1] == "Insertion" || args[1] == "Merge"){
testWithComparisonFunction(args[0], args[1], new RecordComparatorIntField());
}else
System.out.println("Algorithm not found. Use: [ Insertion | Merge ]");
}
在命令行中输入此内容,我做错了什么?
java insertionandmergeusagejava/InsertionAndMer
geUsage "/home/zenoraiser/Scrivania/Università/Secondo Anno/Algoritmi/1718/LAB/Progetto/Integers.txt" "Insertion"
如果将if语句更改==
为.equals
,则会与混淆
if ("Insertion".equals(args[1]) || "Merge".equals(args[1])) {
您应该得到预期的结果。
在Java中,==
操作需要的LHS值并直接与RHS值进行比较,这是原始类型,如细int
,double
等字符串是虽然有点不同。由于字符串实际上是一个字符数组Object
,因此将其存储为,因此==
操作员将比较指向LHS / RHS的指针(在这种情况下,它们不相等)。
您可以使用以下代码观察到看似奇怪的行为:
String a = "Test.";
String b = "Test.";
System.out.println(a == b); // true
System.out.println(a.toLowerCase() == b.toLowerCase()); // false
这是由于称为“字符串插入”的过程所致,该过程可在具有相同值的情况下有效地将多个字符串存储在同一指针下。
还要注意,通过将String文字放在比较中的第一位,可以消除NullPointerException
ifargs[1]
不存在的可能性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句