重新排列代码片段后获得额外的'-'



所以我从Head First Java一书中开始学习Java,并偶然发现了一个练习。我需要重新排列这些代码片段以获得如下所示的输出:

a-b c-d

代码片段是:

if (x == 1) {
System.out.print("d");
x = x - 1
}
if (x == 2) {
System.out.print("b c");
}
if (x > 2) {
System.out.print("a");
}
while (x > 0) {
x = x - 1;
System.out.print("-");
int x = 3;

所以我做了这样的事情:

public class cc {
public static void main(String [] args) {
int x = 3;
while (x > 0) {
if (x == 2) {
System.out.print("b c");
}
if (x > 2) {
System.out.print("a");
}
if (x == 1) {
System.out.print("d");
}
x = x - 1;
System.out.print("-");
}

}
}

我得到的输出是:

a-b c-d-

我做错了什么

您在其中一个 if 语句中错过了一个x = x - 1;,并将 print 语句放在错误的位置:

public class cc {
public static void main(String [] args) {
int x = 3;
while (x > 0) {
if (x == 2) {
System.out.print("b c");
}
if (x > 2) {
System.out.print("a");
}
x = x - 1;
System.out.print("-");
if (x == 1) {
System.out.print("d");
x = x - 1;
}
}
}
}
public class cc {
public static void main(String [] args) {
int x = 3;
while (x > 0) {
if (x == 2) {
System.out.print("b c");
}
if (x > 2) {
System.out.print("a");
}
if (x == 1) {
System.out.print("d");
}
x = x - 1;
System.out.print("-"); // will run for every iteration of the loop
}

}
}

查看此处的代码,在循环的每次迭代后,无论 x 的值如何,它都会在输出后打印一个破折号。您还缺少x = x - 1;

if (x == 1) {
System.out.print("d");
x = x - 1; // you were missing this
}

上面的 if 语句也应该放在下面

x = x - 1;
System.out.print("-");

这样我们就不会添加不必要的 - 最后在检查条件之前设置x == 1,这样我们就不会进行另一次迭代。

把这一切放在一起,我们得到这个

public class cc {
public static void main(String [] args) {
int x = 3;
while (x > 0) {
if (x > 2) {
System.out.print("a");
}
if (x == 2) {
System.out.print("b c");
}
x = x - 1;
System.out.print("-");
if (x == 1) {
System.out.print("d");
x = x - 1;
}
}
}
}

编辑:我还为您重新排列了if语句,因为> 2== 2更合乎逻辑之前出现

练习的重点是理解循环(在本例中为 while 循环)、if 语句和修改存储在变量中的值。为此,我建议还查看数组并尝试生成所需的输出。例如,此特定情况将打印 a-b c-d,但一般情况是什么?如果你有一堆字符,看起来它们将被分成几对,其中每对用空格分隔,在任何给定对的每个元素之间都有一个连字符。

所以假设你有

String input = "abcd";

你必须写什么才能得到

a-b c-d

在输出中?

一种可能性如下

char[] chars = input.toCharArray();
int i = 0;
while (i < chars.length) {
String separator;
System.out.print(chars[i]);
if (i == chars.length - 1) {
separator = "n";
else if (i % 2 != 0) {
separator = " ";
} else {
separator = "-";
}
System.out.print(separator);
i++;
}

最新更新