您所在的位置:首页 - 科普 - 正文科普

java程序设计题及答案

吉花
吉花 05-13 【科普】 736人已围观

摘要**Title:MasteringJavaProgramming:ComprehensiveSolutionstoCodingChallenges**Javaprogrammingisaversati

Title: Mastering Java Programming: Comprehensive Solutions to Coding Challenges

Java programming is a versatile language used across various industries for its robustness and flexibility. Below are comprehensive solutions to common coding challenges in Java:

Question 1: Reverse a String

```java

public class ReverseString {

public static String reverse(String str) {

StringBuilder reversed = new StringBuilder();

for (int i = str.length() 1; i >= 0; i) {

reversed.append(str.charAt(i));

}

return reversed.toString();

}

public static void main(String[] args) {

String original = "hello";

String reversed = reverse(original);

System.out.println("Reversed string: " reversed);

}

}

```

Question 2: Check Palindrome

```java

public class PalindromeCheck {

public static boolean isPalindrome(String str) {

int left = 0;

int right = str.length() 1;

while (left < right) {

if (str.charAt(left) != str.charAt(right)) {

return false;

}

left ;

right;

}

return true;

}

public static void main(String[] args) {

String word = "racecar";

if (isPalindrome(word)) {

System.out.println(word " is a palindrome.");

} else {

System.out.println(word " is not a palindrome.");

}

}

}

```

Question 3: Find Maximum Element in an Array

```java

public class MaxElement {

public static int findMax(int[] arr) {

int max = Integer.MIN_VALUE;

for (int num : arr) {

if (num > max) {

max = num;

}

}

return max;

}

public static void main(String[] args) {

int[] numbers = {5, 2, 9, 1, 7};

int max = findMax(numbers);

System.out.println("Maximum element: " max);

}

}

```

Question 4: Calculate Factorial

```java

public class Factorial {

public static int calculateFactorial(int n) {

if (n == 0 || n == 1) {

return 1;

}

int factorial = 1;

for (int i = 2; i <= n; i ) {

factorial *= i;

}

return factorial;

}

public static void main(String[] args) {

int number = 5;

int factorial = calculateFactorial(number);

System.out.println("Factorial of " number ": " factorial);

}

}

```

Question 5: Check Prime Number

```java

public class PrimeCheck {

public static boolean isPrime(int n) {

if (n <= 1) {

return false;

}

for (int i = 2; i <= Math.sqrt(n); i ) {

if (n % i == 0) {

return false;

}

}

return true;

}

public static void main(String[] args) {

int num = 17;

if (isPrime(num)) {

System.out.println(num " is a prime number.");

} else {

System.out.println(num " is not a prime number.");

}

}

}

```

These solutions provide efficient and concise ways to tackle common coding problems in Java. By understanding and practicing these concepts, you can enhance your proficiency in Java programming and tackle more complex challenges with confidence.

Tags: 字体转换火星文 人曾乱码一二三四 失眠的句子微信朋友圈 熊猫人之谜cg 支付宝崩了

最近发表

icp沪ICP备2023033053号-25
取消
微信二维码
支付宝二维码

目录[+]