I have the following code in java, which takes in input from the user. It is basically a simple database system.
ArrayList<String> commands = new ArrayList<String>();
ArrayList<ArrayList<String>> blocks = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
System.out.println("Enter the transaction commands.\n");
Scanner scan = new Scanner(System.in);
while(!(line = scan.nextLine()).toLowerCase().equals("end"))
{
commands.add(line);
}
for(String com : commands)
{
String split[] = com.split(" ");
if(!split[0].toLowerCase().equals("get") && !split[0].toLowerCase().equals("numequalto") && !split[0].toLowerCase().equals("rollback") && !split[0].toLowerCase().equals("commit"))
{
if(split[0].toLowerCase().equals("begin"))
{
if(!list.isEmpty())
{
blocks.add(list);
System.out.println(blocks.get(0));
list.clear();
}
else
{
continue;
}
}
else
{
list.add(com);
continue;
}
}
}
System.out.println(blocks.get(0));
The input I give for this program is:
set a 10
set b 20
begin
get a
get b
end
While the expected output is:
[set a 10, set b 20]
[set a 10, set b 20]
I get the output as:
[set a 10, set b 20]
[]
The problem seems to be that the value of the ArrayList> blocks, seems to be overwritten. The last print statement prints the value as an empty ArrayList. I cannot find the exact source of error. Any help in finding out the error will be greatly appreciated.