Reputation: 1342
I am trying to find a second largest number from a given string but it's not giving me exact result which I want.
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);
}
}
The output is looking like this
Enter the String 52236 The second largest element is 53
The largest number should be only 5 bit'sits showing me 53 in the output.
Upvotes: 0
Views: 289
Reputation: 262494
The answer is correct (in a way): 53 is the ASCII code for '5'
.
You go over your String as a char[] arr
, and each char
in there is (once you put it into an int
) the Unicode code point of the character.
You could adjust the way it is printed:
System.out.println("The second largest element is "+ (char) second);
or avoid putting it into an int
type variable in the first place (if you keep as a char
it will print as intended).
Also note that your approach is a bit fragile, it will do unexpected things when the input String contains non-digit characters such as letters.
Upvotes: 3