回文循环总是打印 True
Palindrome loop is always printing True
我是新来的,也是 Java 的新手。
我的任务是编写一个循环来检查具有给定结构的回文。
我只被允许使用 for 循环和 if 语句。
这是我的代码。结果始终打印为真。
package palindrom;
/**
*
* @author Edwin
*/
public class Palindromcheck {
static boolean is_palindrom(String str) {
int n = str.length();
for (int i = 0; i <= (n / 2) + 1; ++i) {
if (str.charAt(i) != str.charAt(n - i - 1)) {
return false;
}
}
return true;
}
public static void main (String [] args){
assert(is_palindrom(""));
assert(is_palindrom("a"));
assert(is_palindrom("aa"));
assert(is_palindrom("aba"));
assert(!is_palindrom("abab"));
assert(!is_palindrom("abb"));
if (true)
System.out.println("Everything good!");
}
}
据我所知,您的代码运行良好。 None 的断言应该触发,因为您在所有不是回文的字符串之前放置了一个 not !
。
最后一个 println 周围的 "if (true)" 位有点奇怪。它什么都不做,因为 true 永远是 true。
我想指出,即使您删除了 !
s 正如 Daniel T 所建议的(不过你真的应该删除它们)。
例如,如果您使用标准 JVM 设置编译并执行以下命令:
class Example {
public static boolean yieldFalse() {
return false;
}
public static void main(String[] args) {
assert(yieldFalse());
System.out.println("No error!");
}
}
你会发现"No error!"每次都打印到标准输出。这是因为默认情况下 JVM 不启用断言。
如果您查看 this answer,您将了解如何启用它们。但是,您可能更方便地编写以下内容,这样任何人 运行 您的代码都将获得您想要的输出:
if (!is_palindrom("string")) {
// throw an exception or print to the console
// "string" is not a palindrome
}
除了关于断言的那一点,行
for (int i = 0; i <= (n / 2) + 1; ++i)
不太对。如果 n
是 0
或 1
,(n / 2) + 1
是 1
,那么这两种情况都会导致 StringIndexOutOfBoundsException
。正确的条件是:
for (int i = 0; i < (n + 1) / 2; ++i)
我是新来的,也是 Java 的新手。 我的任务是编写一个循环来检查具有给定结构的回文。 我只被允许使用 for 循环和 if 语句。 这是我的代码。结果始终打印为真。
package palindrom;
/**
*
* @author Edwin
*/
public class Palindromcheck {
static boolean is_palindrom(String str) {
int n = str.length();
for (int i = 0; i <= (n / 2) + 1; ++i) {
if (str.charAt(i) != str.charAt(n - i - 1)) {
return false;
}
}
return true;
}
public static void main (String [] args){
assert(is_palindrom(""));
assert(is_palindrom("a"));
assert(is_palindrom("aa"));
assert(is_palindrom("aba"));
assert(!is_palindrom("abab"));
assert(!is_palindrom("abb"));
if (true)
System.out.println("Everything good!");
}
}
据我所知,您的代码运行良好。 None 的断言应该触发,因为您在所有不是回文的字符串之前放置了一个 not !
。
最后一个 println 周围的 "if (true)" 位有点奇怪。它什么都不做,因为 true 永远是 true。
我想指出,即使您删除了 !
s 正如 Daniel T 所建议的(不过你真的应该删除它们)。
例如,如果您使用标准 JVM 设置编译并执行以下命令:
class Example {
public static boolean yieldFalse() {
return false;
}
public static void main(String[] args) {
assert(yieldFalse());
System.out.println("No error!");
}
}
你会发现"No error!"每次都打印到标准输出。这是因为默认情况下 JVM 不启用断言。
如果您查看 this answer,您将了解如何启用它们。但是,您可能更方便地编写以下内容,这样任何人 运行 您的代码都将获得您想要的输出:
if (!is_palindrom("string")) {
// throw an exception or print to the console
// "string" is not a palindrome
}
除了关于断言的那一点,行
for (int i = 0; i <= (n / 2) + 1; ++i)
不太对。如果 n
是 0
或 1
,(n / 2) + 1
是 1
,那么这两种情况都会导致 StringIndexOutOfBoundsException
。正确的条件是:
for (int i = 0; i < (n + 1) / 2; ++i)