When I try to redefine a variable, I get an index out of bounds error
Posted
by
user2770254
on Stack Overflow
See other posts from Stack Overflow
or by user2770254
Published on 2013-10-26T21:50:10Z
Indexed on
2013/10/26
21:53 UTC
Read the original article
Hit count: 198
I'm building a program to act as a calculator with memory, so you can give variables and their values. Whenever I'm trying to redefine a variable, a = 5, to a = 6, I get an index out of bounds error.
public static void main(String args[])
{
LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
Scanner scan = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
ArrayList<String> variables = new ArrayList<>();
while(scan.hasNextLine())
{
String line = scan.nextLine();
String[] tokens = line.split(" ");
if(!Character.isDigit(tokens[0].charAt(0)) && !line.equals("clear") && !line.equals("var"))
{
int value = 0;
for(int i=0; i<tokens.length; i++)
{
if(tokens.length==3)
{
value = Integer.parseInt(tokens[2]);
System.out.printf("%5d\n",value);
if(map.containsKey(tokens[0]))
{
values.set(values.indexOf(tokens[0]), value);
variables.set(variables.indexOf(tokens[0]), tokens[0]);
}
else
{
values.add(value);
}
break;
}
else if(tokens[i].charAt(0) == '+')
{
value = addition(tokens, value);
System.out.printf("%5d\n",value);
variables.add(tokens[0]);
if(map.containsKey(tokens[0]))
{
values.set(values.indexOf(tokens[0]), value);
variables.set(variables.indexOf(tokens[0]), tokens[0]);
}
else
{
values.add(value);
}
break;
}
else if(i==tokens.length-1 && tokens.length != 3)
{
System.out.println("No operation");
break;
}
}
map.put(tokens[0], value);
}
if(Character.isDigit(tokens[0].charAt(0)))
{
int value = 0;
if(tokens.length==1)
{
System.out.printf("%5s\n", tokens[0]);
}
else
{
value = addition(tokens, value);
System.out.printf("%5d\n", value);
}
}
if(line.equals("clear"))
{
clear(map);
}
if(line.equals("var"))
{
variableList(variables, values);
}
}
}
public static int addition(String[] a, int b)
{
for(String item : a)
{
if(Character.isDigit(item.charAt(0)))
{
int add = Integer.parseInt(item);
b = b + add;
}
}
return b;
}
public static void clear(LinkedHashMap<String,Integer> b)
{
b.clear();
}
public static void variableList(ArrayList<String> a, ArrayList<Integer> b)
{
for(int i=0; i<a.size(); i++)
{
System.out.printf("%5s: %d\n", a.get(i), b.get(i));
}
}
I included the whole code because I'm not sure where the error is arising from.
© Stack Overflow or respective owner