why does the system.exit work for the first if statement. but if not typing anything in the second Joption only gets you error with following code "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48) at java.base/java.lang.String.charAt(String.java:711) at string.counter.stringcounter.main(stringcounter.java:37) "
import javax.swing.JOptionPane;
// following is a several function that togheter makes the class of a stringcounter //including a loop, dialogboxes etc
public class stringcounter {
//variable declaration
public static void main(String[] args) {
String inpSentence, countChar;
int charCounter, sent;
char inpChar, currentChar;
charCounter = 0;
//variable declaration
inpSentence = JOptionPane.showInputDialog("Enter a string:");
if (inpSentence.equals(""))
JOptionPane.showMessageDialog
(null, "You must make an entry in the input box");
if (inpSentence.equals("")) System.exit(0);
countChar =JOptionPane.showInputDialog("Enter a letter:");
inpChar = countChar.charAt(0);
if (countChar.equals(""))
JOptionPane.showMessageDialog
(null, "You must make an entry in the input box");
if (countChar.equals("")) System.exit(0);
sent = inpSentence.length();
//indexcounter for characters starting at 0
for (int i = 0; i < sent; i++ ) {
currentChar = inpSentence.charAt(i);
//if to compare input against sentence
if (currentChar == inpChar) {
charCounter += 1;
}
// Display the result
JOptionPane.showMessageDialog(null, "' Meningen '" + inpSentence + "' innehåller '" + sent + "' bokstäver. '" + countChar + "' förekommer '" + +charCounter + "'gång '" );
}
}
}
Aucun commentaire:
Enregistrer un commentaire