'How to add items to a list of lists
I aim to print a list of lists containing entry and exit times in the 24 hour decimal format from the "AM"-"PM" String format input by the user as a String array like this: {6AM#8AM, 11AM#1PM, 7AM#8PM, 7AM#8AM, 10AM#12PM, 12PM#4PM, 1PM#4PM, 8AM#9AM}
I declared the individual lists inside the for loop and assigned them values inside the loop but got the following run time exception from my code: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Kindly help me debug my code:
import java.util.*;
public class TimeSchedule
{
public static List<List<Integer>> Timein24hourFormat(String[] input1)
{
List<List<Integer>> scheduledTime = new ArrayList<List<Integer>>();
int [] exitTime = new int[input1.length];
int [] entryTime = new int[input1.length];
for (int i=0;i<input1.length;i++)
{
List<String> listOfStrings = new ArrayList<>();
List<Integer> tempList = scheduledTime.get(i);
String[] timeSlot = input1[i].split("#");
for (int m=0;m<2;m++)
{
listOfStrings.add(timeSlot[m]);
if (listOfStrings.contains("AM"))
{
listOfStrings.remove("AM");
tempList.add(Integer.parseInt(listOfStrings.get(m)));
}
if (listOfStrings.contains("PM") && timeSlot[m].contains("12"))
{
listOfStrings.remove("PM");
tempList.add(Integer.parseInt(listOfStrings.get(m)));
}
if (listOfStrings.contains("PM") && !timeSlot[m].contains("12"))
{
listOfStrings.remove("PM");
tempList.add((Integer.parseInt(listOfStrings.get(m))) + 12);
}
}
}
return scheduledTime;
}
public static void main (String[]args)
{
Scanner input = new Scanner(System.in);
int customersNumber = input.nextInt();
input.nextLine();
String [] entryExitTime = new String[customersNumber];
for (int i=0;i<customersNumber;i++)
{
entryExitTime[i] = input.nextLine();
}
System.out.println(Timein24hourFormat(entryExitTime));
}
}
Solution 1:[1]
public static List<List<Integer>> Timein24hourFormat(String[] input1)
{
List<List<Integer>> scheduledTime = new ArrayList<List<Integer>>();
int [] exitTime = new int[input1.length];
int [] entryTime = new int[input1.length];
for (int i=0;i<input1.length;i++)
{
List<String> listOfStrings = new ArrayList<>();
List<Integer> tempList = scheduledTime.get(i);
String[] timeSlot = input1[i].split("#");
scheduledTime is empty at this stage and that's why you can not retrieve value and you get IndexOutOfBoundsException
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |