在Java中,我们可以使用多种方法来实现复杂逻辑。以下是一些建议:
int a = 10;
int b = 20;
int result;
if (a > b) {
result = a + b;
} else {
result = a - b;
}
int number = 2;
switch (number) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
default:
System.out.println("Invalid number");
}
// for loop
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration " + i);
}
// while loop
int j = 1;
while (j <= 5) {
System.out.println("Iteration " + j);
j++;
}
// do-while loop
int k = 1;
do {
System.out.println("Iteration " + k);
k++;
} while (k <= 5);
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int number : numbers) {
sum += number;
}
System.out.println("Sum: " + sum);
public class ComplexLogic {
public static void main(String[] args) {
int a = 10;
int b = 20;
int result = add(a, b);
System.out.println("Result: " + result);
}
public static int add(int a, int b) {
return a + b;
}
}
import java.util.Arrays;
import java.util.List;
public class ComplexLogic {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println("Sum: " + sum);
}
}
根据你的需求,可以选择合适的方法来实现复杂逻辑。在Java中,通常可以通过组合这些基本结构来构建更复杂的逻辑。