gpt4 book ai didi

java - 堆栈返回对象而不是整数

转载 作者:行者123 更新时间:2023-12-02 00:37:00 24 4
gpt4 key购买 nike

我正在尝试实现一个涉及堆栈数组的程序。每个堆栈都接受 Integer 对象,但问题是当我尝试从堆栈中获取 Integer 对象时:

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)
{

}
}

该错误表明无法识别 .intValue()。显然这是 Integer 的一个方法,从那时起我发现它返回的是 Object 对象而不是 Integer 类型。如何让它返回整数类型?

最佳答案

要定义泛型数组,您需要执行此操作。

@SuppressWarnings("unchecked") // to avoid warnings.
Stack<Integer>[] blocks = new Stack[n];

然后你就可以写了

int holder = blocks[fromBlock].pop();

是的,它确实可以编译并且工作得很好。

编辑:为什么编译器不能让你这样做

Stack<Integer>[] blocks = new Stack<Integer>[n];

Stack<Integer>[] blocks = new Stack<>[n];

我无法理解同一件事的含义。

关于java - 堆栈返回对象而不是整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7563753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com