I have to write a function that accepts a string and returns the second highest numerical digit in the user input as an integer. These are the rules I have to follow:
My code:
public static int secondDigit(String input) {
try {
int userInput = Integer.parseInt(input);
char[] array = input.toCharArray();
int biggest = Integer.MIN_VALUE;
int secondBiggest = Integer.MIN_VALUE;
for(int i =0; i < array.length; i++)
{
System.out.println("Array: "+array[i]);
for(int j = 0; j < array[i]; j++)
{
if(array[i] > biggest)
{
secondBiggest = biggest;
biggest = array[i];
}
else if(array[i] > secondBiggest && array[i] != biggest)
{
secondBiggest = array[i];
}
}
}
System.out.println(secondBiggest);
return userInput;
}catch(Exception e) {
System.out.println("-1");
}
return -1;
// Your code goes here
}
"abc:1231234" should return 3
"123123" should return 3
Currently this is the code and it returns 51 when i give it an input of "123123".
Your code is almost correct, the only problem is that what you print is the char at that position, the char is '3'
and has an ascii value of 51
. To fix this you need to parse an int from the char.