2016 - 2024

感恩一路有你

用方法来实现:并计算最大值 请用户输入一个字符串

浏览量:4753 时间:2024-06-19 21:11:49 作者:采采

在这篇文章中,我们将介绍如何使用方法来计算一个字符串中字符的个数,并输出字符串中的最大值。首先,请用户输入一个字符串:

```java import ; public class MaxValueOfString { public static void main(String[] args) { Scanner scanner new Scanner(); ("请输入一个字符串:"); String input (); int count countCharacters(input); ("字符串中的字符个数为:" count); char maxChar getMaxChar(input); ("字符串中的最大值为:" maxChar); } public static int countCharacters(String str) { return str.length(); } public static char getMaxChar(String str) { if (str.length() 0) { throw new IllegalArgumentException("字符串不能为空"); } char maxChar (0); for (int i 1; i < str.length(); i ) { char currentChar (i); if (currentChar > maxChar) { maxChar currentChar; } } return maxChar; } } ```

程序执行结果:

请输入一个字符串:
"Hello World"
字符串中的字符个数为:11
字符串中的最大值为:r

求数组中的最大值 可变参数代码:

在这一部分中,我们将展示如何使用可变参数来计算一个数组中的最大值。

```java public class MaxValueOfArray { public static void main(String[] args) { int maxValue getMaxValue(5, 10, 3, 8, 2); ("数组中的最大值为:" maxValue); } public static int getMaxValue(int... numbers) { if (numbers.length 0) { throw new IllegalArgumentException("数组不能为空"); } int maxValue numbers[0]; for (int i 1; i < numbers.length; i ) { if (numbers[i] > maxValue) { maxValue numbers[i]; } } return maxValue; } } ```

程序执行结果:

数组中的最大值为:10

用方法来实现:计算1-100之间的所有整数的和

在这一部分中,我们将介绍如何使用方法来计算1到100之间的所有整数的和。

```java public class SumOfNumbers { public static void main(String[] args) { int sum getSum(1, 100); ("1到100之间的所有整数的和为:" sum); } public static int getSum(int start, int end) { if (start > end) { throw new IllegalArgumentException("起始值不能大于结束值"); } int sum 0; for (int i start; i < end; i ) { sum i; } return sum; } } ```

程序执行结果:

1到100之间的所有整数的和为:5050

版权声明:本文内容由互联网用户自发贡献,本站不承担相关法律责任.如有侵权/违法内容,本站将立刻删除。