使用嵌套if else语句进行字符串连接

时间:2016-02-24 13:54:59

标签: java if-statement statements

我正在审核测试。有人能告诉我我的代码有什么问题吗?它适用于问题5E。不明白为什么这不会运行。 “最后,编写上一个练习中的代码的修改版本,5。(D)”

enter image description here

 public static void main(String[] args) 
    {
     int i = 12;
     int j = 10; 
     int m = 14;
     int n = 6;
     int numComparisons = 0;
     String comparisons = null;

     System.out.print("Madam");
     numComparisons++;
     comparisons =  comparisons + i + " < " + j;
     if (i < j)
     { 
     comparisons = comparisons + "? (T),";
     numComparisons++;
     if (m != n) 
     {
     comparisons = comparisons + m + "!=" + n  + "? (T),";
     System.out.print("How");
     }
     else
     {
     comparisons + m + "!=" + n  + "? (F),";
     System.out.print("Now");
     }
     }   
     System.out.print("I’m");
     numComparisons++;
     if (i >= m)
     {
     comparisons = comparisons + i + " >= " + m + "? (T),";
     System.out.println("Cow");
     }
     else
     { 
     comparisons = comparisons + i + " >= " + m + "? (T),";
     System.out.println("Adam"); 
     System.out.println("Number of comparisons: " + numComparisons);
     }
    System.out.println(comparisons);
    }
}

2 个答案:

答案 0 :(得分:2)

您的代码中的以下行似乎有误:

comparisons + m + "!=" + n + "? (F),";

但是,如果您将此行更改为:

comparisons = m + "!=" + n + "? (F),";

它编译得很好,你会得到这个输出:

  

MadamI'mAdam   比较次数:2   null12&lt; 1012> = 14? (T),

答案 1 :(得分:0)

comparisons + m + "!=" + n + "? (F),";不是有效的Java。

你可能意味着comparisons = comparisons + m + "!=" + n + "? (F),";和其他所有情况一样。