Java是一種廣泛使用的編程語言,許多人學(xué)習(xí)Java時需要練習(xí)一些編程題來提高自己的編程技能。下面是一些經(jīng)典的Java練習(xí)題以及它們的答案。
題目1:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
答案1:
Hello World!
題目2:
public class SumOfNumbers {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i<= 100; i++) {
sum += i;
}
System.out.println("The sum of numbers from 1 to 100 is " + sum);
}
}
答案2:
The sum of numbers from 1 to 100 is 5050
題目3:
public class Fibonacci {
public static void main(String[] args) {
int n = 10, t1 = 0, t2 = 1;
System.out.print("First " + n + " terms: ");
for (int i = 1; i<= n; ++i) {
System.out.print(t1 + " + ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}
答案3:
First 10 terms: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 +
題目4:
public class Rectangle {
int length, width;
public Rectangle(int length, int width) {
this.length = length;
this.width = width;
}
public int getArea() {
return length * width;
}
}
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 10);
System.out.println("The area of the rectangle is " + rectangle.getArea());
}
}
答案4:
The area of the rectangle is 50
以上就是一些Java練習(xí)題以及它們的答案,希望這些練習(xí)題能夠幫助大家提高自己的編程技能。