The try-catch is supposed to catch if the user doesn't input anything on both or just one of them but right now it does nothing. It crashes if you input a sentence but not a Character but not vice versa. I'm quite new to Java but here is what I have:
import javax.swing.*;
public class Main {
public static void main(String[] args) {
countSentence();
}
static void countSentence() {
String input;
char ch;
int count = 0;
int countLetters = 0;
input = JOptionPane.showInputDialog(null, "Write a sentence");
ch = JOptionPane.showInputDialog(null, "Write a character").charAt(0);
if (!input.equals("") || ch != ' ') {
try {
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) != ' ')
count++;
}
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ch)
countLetters++;
}
JOptionPane.showMessageDialog(null,
"The sentence has " + count + " characters \n" + "The character " + ch
" occurs " + countLetters + " times. " +
"First time at index place " + input.indexOf(ch) +
"\n Last time at index place " + input.lastIndexOf(ch));
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, "You need to input both a sentence and a character!");
}
}
}
}
Here your a referencing the char at the first position
ch = JOptionPane.showInputDialog(null, "Write a character").charAt(0);
But if the user does not enter something the code fails with an index out of range Exception.
I would do a rewrite like this
static void countSentence() {
String input;
String ch;
int count = 0;
int countLetters = 0;
input = JOptionPane.showInputDialog(null, "Write a sentence");
ch = JOptionPane.showInputDialog(null, "Write a character");
if (input.equals("") || ch.equals("")) {
JOptionPane.showMessageDialog(null, "You need to input both a sentence and a character!");
} else {
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) != ' ')
count++;
}
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ch.charAt(0))
countLetters++;
}
JOptionPane.showMessageDialog(null,
"The sentence has " + count + " characters \n" + "The character " + ch +
" occurs " + countLetters + " times. " +
"First time at index place " + input.indexOf(ch) +
"\n Last time at index place " + input.lastIndexOf(ch));
}
} }
Do not use try-catch for Flow Control. See: https://wiki.c2.com/?DontUseExceptionsForFlowControl