I’m trying to implement a program that involves an array of stacks. Each stack takes in Integer objects, but the problem is when I try to get an Integer object from the stack:
import java.util.*;
public class Blocks
{
public static void main(String[] args)
{
System.out.println();
Scanner input = new Scanner(System.in);
Stack[] blocks = new Stack[input.nextInt()];
for (int i = 0; i < blocks.length; i++) {blocks[i] = new Stack<Integer>();} //initializing main array of stacks of blocks
for (int i = 0; i < blocks.length; i++) {blocks[i].push(i);} //add first block to each stack
Stack retainer = new Stack<Integer>(); //used for when moving stacks of blocks instead of one block.
boolean m; //move or pile
boolean on; //onto or over
int fromBlock; //block being moved
int toBlock; //block where the fromBlock is being moved
String command = input.next();
while (!command.equals("quit"))
{
m = command.equals("move");
fromBlock = input.nextInt();
on = input.next().equals("onto");
toBlock = input.nextInt();
if (m) //put back blocks on fromBlock
{
if (on) //put back blocks on toBlock
{
int holder = blocks[fromBlock].pop().intValue(); //I get a compiler error here
moveOnto(blocks, holder, toBlock);
}
else //fromBlock goes on top of stack on toBlock
{
}
}
else //bring blocks on fromBlock
{
if (on) //put back blocks on toBlock
{
}
else //fromBlock goes on top of stack on toBlock
{
}
}
command = input.next();
}
}
void moveOnto(Stack[] array, int sBlock, int rBlock)
{
}
}
The error says that is doesn’t recognize .intValue(). Obviously that is a method of Integer, and I found out from that point that it’s returning Object objects instead of Integer types. How can I make it return Integer types?
(oops – Java doesn’t allow arrays of generics)
Change yourStackvariable declaration to use the generic version ofStack:Otherwise when you access the non-generic stack’s
.pop()method it just returns an Object which you would need to cast back to an Integer In order to access Integer methods like intValue():(But you won’t need to cast if you fix the declarations.)