在编程的世界里,有时候我们会编写一些出乎意料的、有趣的或甚至是愚蠢的代码。这些糟糕的代码和有趣的失误是程序员生活中的一部分,让我们一起来欣赏一下。
1. “Hello World!” 复杂版
public class HelloWorld {
public static void main(String[] args) {
String greetings = "Hello World!";
for (int i = 0; i < greetings.length(); i++) {
System.out.print(greetings.charAt(i));
}
}
}
这段代码的任务是打印出 “Hello World!”,但却把它复杂化了,使用一个循环和时间延迟,逐字母地打印出来。
2. 循环危机
var i = 0;
while (i != 10) {
i += 0.1;
}
这段代码的目标是让 i 逐渐增加到10,但由于浮点数精度问题,它会导致无限循环,i 永远不会等于10。
3. 溢出的爱
#include <stdio.h>
int main() {
int love = 1;
while (love > 0) {
printf("I love programming!\n");
love++;
}
return 0;
}
这段代码试图展示对编程的热爱,但它在 love 变量溢出后会进入一个无限循环。
4. 无限递归
public class InfiniteRecursion {
public static void countToInfinity(int n) {
System.out.println(n);
countToInfinity(n + 1);
}
public static void main(String[] args) {
countToInfinity(1);
}
}
这个函数试图无限递增并打印数字,但它会导致栈溢出错误,因为递归没有基本情况来停止。
5. 日期迷宫
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateMaze {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
String dateString = sdf.format(date);
System.out.println("Today's date is: " + dateString);
}
}
这段Java代码试图打印当前日期,但它却使用了错误的日期格式,导致日期迷宫,通常会输出一些奇怪的日期格式。
6. 数组颠倒
public class ArrayReversal {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int i = numbers.length; i >= 0; i--) {
System.out.println(numbers[i]);
}
}
}
这段Java代码试图颠倒一个整数数组的元素,但它的循环索引错误,会导致 ArrayIndexOutOfBoundsException 错误。
你还遇到过什么有趣的代码呢?请在评论区交流分享吧!

本文含有隐藏内容,请 开通VIP 后查看