因此,我从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-我做错了什么?
发布于 2020-08-22 02:15:42
您在一条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;
}
}
}
}发布于 2020-08-22 02:58:57
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
发布于 2020-08-22 02:37:18
本练习的重点是理解循环(在本例中是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++;
}https://stackoverflow.com/questions/63527994
复制相似问题