Java问题-奇数偶数

时间:2018-11-20 19:28:27

标签: java

作为示例,我正在努力从用户输入中获取输出,以仅显示奇数或偶数(如果第一个CharAt(0) == 'w')。

它通过“ System.out.println(CharAt(0)+ CharAt(2)+ CharAt(4))”起作用吗?

我正在使用Scanner项目获取用户输入,并且已经具有以下输入部分:

Scanner input = new Scanner(System.in);
System.out.print("Please enter a uncoded string: ");
String first = input.nextLine();
input.close();

if (first.charAt(0) == 'u') {
  first = first.toUpperCase();
} else if (first.charAt(0) == 'l') {
  first = first.toLowerCase();
} else if (first.charAt(0) == 'o') {
      first = first.charAt(0) + charAt(2) + charAt (4);
}

System.out.println("The decoded string is: " + first);

有没有只拥有(0 +奇数)这样的公式的方法?

1 个答案:

答案 0 :(得分:1)

我猜您正在尝试通过检查其前缀char来“解码”一个“编码”字符串:

Scanner input = new Scanner(System.in);
System.out.print("Please enter a uncoded string: ");
String first = input.nextLine();
input.close();

if (first.charAt(0) == 'u') {
    first = first.toUpperCase();
} else if (first.charAt(0) == 'l') {
    first = first.toLowerCase();
} else if (first.charAt(0) == 'o') {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < first.length(); i = i + 2) {
        sb.append(first.charAt(i));
    }
    first = sb.toString();
} else if (first.charAt(0) == 'e') {
    StringBuilder sb = new StringBuilder();
    for (int i = 1; i < first.length(); i = i + 2) {
        sb.append(first.charAt(i));
    }
    first = sb.toString();
}
System.out.println("The decoded string is: " + first);

我不确定在前缀“ o”的情况下是否要将此前缀包含在结果中。
编辑
如果您不喜欢StringBuilder:

} else if (first.charAt(0) == 'o') {
    String str = "";
    for (int i = 0; i < first.length(); i = i + 2) {
        str += first.charAt(i);
    }
    first = str;
} else if (first.charAt(0) == 'e') {
    String str = "";
    for (int i = 1; i < first.length(); i = i + 2) {
        str += first.charAt(i);
    }
    first = str;
}