为什么要打印一个单词?

时间:2014-07-06 01:09:51

标签: java

public class printEveryOther{
public static String printEveryOther(String x){
    for (int i = 0; i < x.length(); i = i+2){
        System.out.print (x.charAt(i));
    }
    return x;
}

public static void main (String[] args){
    String x = "method";
    String y = printEveryOther(x);
    System.out.println(y);
}

}

当此代码运行时,我希望它生成mto。它打印字符串的每个其他字符。然而,这个输出是mtomethod。为什么呢?

3 个答案:

答案 0 :(得分:2)

因为你有额外的印刷品(换句话说,y = "method") -

public static String printEveryOther(String x){
  for (int i = 0; i < x.length(); i = i+2){
    System.out.print (x.charAt(i));
  }
  return x; // <-- return the input "x" (that is "method")
}

public static void main (String[] args){
  String x = "method";
  String y = printEveryOther(x);
  // System.out.println(y); // <-- y = "method"
}

答案 1 :(得分:2)

您在两个功能中都使用print。您的printEveryOther函数使用print,然后返回原始字符串,您也println

答案 2 :(得分:1)

因为您有System.out.println(y); ...