The problem in question is indentifying if a string has a comma and outputting the substrings from the original string.
Here is my code:
import java.util.Scanner;
import java.util.*;
import java.io.*;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String fullString = "";
int checkForComma = 0;
String firstSubstring = "";
String secondSubstring = "";
boolean checkForInput = false;
while (!checkForInput) {
System.out.println("Enter input string: ");
fullString = scnr.nextLine();
if (fullString.equals("q")) {
checkForInput = true;
}
else {
checkForComma = fullString.indexOf(',');
if (checkForComma == -1) {
System.out.println("Error: No comma in string");
fullString = scnr.nextLine();
}
else {
continue;
}
firstSubstring = fullString.substring(0, checkForComma);
secondSubstring = fullString.substring(checkForComma + 1, fullString.length());
System.out.println("First word: " + firstSubstring);
System.out.println("Second word: " + secondSubstring);
System.out.println();
System.out.println();
}
}
return;
}
}
The error I keep receiving when I compile is this:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 10
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319)
at java.base/java.lang.String.substring(String.java:1874)
at ParseStrings.main(ParseStrings.java:34)
I'm still somewhat new to programming and have never seen this type of error before, what are some ways to solve this and what might be causing it?