【发布时间】:2015-07-22 18:23:40
【问题描述】:
我正在玩解析整数。我给我的程序输入一行整数。删除所有空格。那么逻辑是这样的:
If I get a 0,
If the next char is 1,
Print out a 0
If the next char is 0,
Print out a 1
Forget the 2 chars I just checked
If I get a 1,
If the next char is 0,
Print out a 1
If the next char is 1,
print out a 0
Forget the 2 chars I just checked
所以输入 10100 1011011 00,我应该得到 1100101。这是我目前的代码:
import java.util.Scanner;
public class Blah {
public static void main (String args[]) {
Scanner input = new Scanner(System.in);
String text = input.nextLine();
int i;
for (i = 0; i < text.length(); i++) {
if (text.charAt(i) == '0') {
if (text.charAt(i++) == '1') {
System.out.print("0");
} else if (text.charAt(i++) == '0') {
System.out.print("1");
}
if (i < text.length())
i++;
} else {
if (text.charAt(i++) == '0') {
System.out.print("1");
i++;
} else if (text.charAt(i++) == '1') {
System.out.print("0");
}
if (i < text.length())
i++;
}
}
}
}
但是,这并没有给我预期的结果。请帮忙。谢谢。
【问题讨论】:
-
它给你什么结果是?为什么它会给你这个结果(调试代码揭示了什么)?
-
我认为您对
i++的确切行为犯了一个错误 - 如果您的第一个条件不正确,我认为您不想增加两次。另外,我想你想做++i如果有的话。 -
一次,我的 01 转换为 1 而不是 0 @SotiriosDelimanolis
-
另外,取出所有空格的代码也不起作用@SotiriosDelimanolis
标签: java input encoding char decoding