I am trying to check for integers, "" and " " when a user inputs a string. Every thing is working as expected but when I pass an empty field it validates and prints invalid input. Apart from that it also prints the println statement from the catch. Below is my code and actual output.
package com.assessment;
import java.util.Scanner;
public class MaxCharString {
public static void main(String[] args) {
int i, j, count = 0, maxcount = 0;
System.out.println("Enter a string to find the maximum character.");
Scanner input = new Scanner(System.in);
String character = input.nextLine().toLowerCase();
try {
if (character == "") {
System.out.println("Invalid Input");
}
int inputCharacter = Integer.parseInt(character);
System.out.println(inputCharacter + " is not a valid Input. Please try again.");
} catch (NumberFormatException e) {
char result = 0;
char ch[] = character.toCharArray();
for (i = 0; i < ch.length; i++) {
count = 0;
for (j = 0; j < ch.length; j++) {
if (ch[i] == ch[j]) {
count++;
}
if (maxcount < count) {
maxcount = count;
result = ch[i];
}
}
}
System.out.println("Maximum count of occuring character in the string is: " + result);
input.close();
}
}
}
Output:
Invalid Input
Maximum count of occuring character in the string is:
Could anyone please help me out with this problem. Thank you.