我试图从给定字符串中找到第二大数字,但它没有给出我想要的确切结果。
import java.util.Scanner;
public class SecondLargest {
public static void secondlarge(char[] arr,int arr_size) {
int i,first,second;
first = second = Integer.MIN_VALUE;
for(i = 0 ; i < arr_size ; i++) {
if (arr[i] > first) {
second =first;
first= arr[i];
}
else if (arr[i] > second && arr[i] != first)
second = arr[i];
}
if (second == Integer.MIN_VALUE)
System.out.println("There is no second largest element\n");
else
System.out.println("The second largest element is "+second);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the String ");
String userString = scan.nextLine();
char[] stringToCharArray = userString.toCharArray();
int n = stringToCharArray.length;
secondlarge(stringToCharArray, n);
}
}
输出看起来像这样
Enter the String 52236 The second largest element is 53
最大的数字应该只有 5 位,在输出中显示为 53。
最佳答案
答案是正确的(在某种程度上):53 是 '5'
的 ASCII 代码。
您将字符串作为 char[] arr
进行检查,其中的每个 char
都是(一旦您将其放入 int
) 字符的 Unicode 代码点。
您可以调整它的打印方式:
System.out.println("The second largest element is "+ (char) second);
或者避免首先将其放入 int
类型变量中(如果保留为 char
,它将按预期打印)。
另请注意,您的方法有点脆弱,当输入字符串包含字母等非数字字符时,它会做出意想不到的事情。
关于java - 错误是从java中的给定字符串中查找第二大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53827106/