Hi iam unable to figure runtime error in below problem, Please can anyone resolve
import java.util.Scanner;
class Solution6 {
public static void main(String[] args)
{
boolean condition = false;
do
{
Scanner scanner = new Scanner(System.in);
String value = scanner.nextLine();
condition = value.equalsIgnoreCase("exit");
if(!condition && value.contains(","))
{
calculate(value);
}
} while (!condition);
}
private static void calculate(String value)
{
final String[] event1 = value.split(",");
int ss = 0;
for ( int i = 0; i < event1[0].length(); ++i )
{
char c = event1[0].charAt( i );
ss += (int) c;
}
int sd = 0;
for ( int i = 0; i < event1[1].length(); ++i )
{
char c = event1[1].charAt( i );
sd += (int) c;
}
System.out.println(ss-sd);
}
}
The problem is that if the user provides an input with a comma (
,) and the comma is the last character (or the only character), thenevent1will have at most 1 element:event1[0]. The elementevent1[1]will not exist, so you get anArrayIndexOutOfBoundsException.This only happens if the input is like this:
bgh,,afsfgf,or even,.You can solve this by checking the number of elements that the array
event1contains.