gpt4 book ai didi

java - 列表数组(Int,Int)

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:51:32 26 4
gpt4 key购买 nike

如您所见,我是面向对象编程的新手。我正在尝试自学,但我被困在这个问题上,不知道该怎么做。

我正在尝试编写一些代码来将矩形网格布置成行和列。想想“将小方 block 布置到大矩形上”。用户将输入他们有多少个“小方 block ”。我的目标是将这个整数映射到行和列的最佳布局。

用户可以输入 20 到 100 之间的任何整数。对于 81 个不同的可能条目中的每一个,我已经确定了以行和列的方式布置这些小方 block 的最佳方式。我现在需要做的是将这 81 种不同的布局放入我的程序中,然后识别并返回适用于用户输入的布局。

因为只有 81 个值,并且它们的范围是连续的整数,所以我认为数组是最好的主意(而不是映射、 HashMap 、 vector 等)。这是我到目前为止所拥有的。有点乱,但我想你会明白我想做什么。谁能帮我?我似乎无法返回我需要的行值和列值。

谢谢!

public static void getLayout (int numSquares) {

int rows;
int columns;

Layouts myLayout = new Layouts();

rows = myLayout[numSquares].r; //this is where it fails
columns = myLayout[numSquares].c;
}

class RowCol<R, C> {

/* Class Variables */
public final R r;
public final C c;

public RowCol(R r, C c) {
this.r = r;
this.c = c;
}

public R getRow() {return r;}
public C getCol() {return c;}
}

class Layouts {

RowCol[] myLayouts;

public Layouts() {

/* Set the numbers of Rows and Columns for each possible
* number of squares requested.
*/
myLayouts[20] = new RowCol(5, 4); // 20 Problems
myLayouts[21] = new RowCol(7, 3); // 21 Problems
myLayouts[22] = new RowCol(5, 4); // 22 Problems
myLayouts[23] = new RowCol(5, 4); // 23 Problems
myLayouts[24] = new RowCol(6, 4); // 24 Problems
myLayouts[25] = new RowCol(5, 5); // 25 Problems
myLayouts[26] = new RowCol(6, 4); // 26 Problems
myLayouts[27] = new RowCol(6, 4); // 27 Problems
myLayouts[28] = new RowCol(7, 4); // 28 Problems
//etc...

编辑:应用下面的响应,我需要在 Layouts 类中实例化一个对象,我做到了。然后,我修改了 getLayout 类以隔离返回的 RowCol 值。这是更新的类(class)。我现在的问题是我无法将行和列转换为整数,以便我可以这样使用它们。

public static void getLayout(int numSquares) {

Layouts myLayout = new Layouts();
RowCol myRC = myLayout.getLayout(numProbs);
int rows = Integer.parseInt(myRC.getRow());
int cols = Integer.parseInt(myRC.getCol());
}

错误是:

no suitable method found for parseInt(Object) method Integer.parseInt(String) is not applicable (actual argument Object cannot be converted to String by method invocation conversion) method Integer.parseInt(String,int) is not applicable (actual and formal argument lists differ in length)

编辑:已解决。谢谢大家!

最佳答案

我可以在那里看到一个快速的问题。布局类不以任何方式支持基于索引的访问。所以下面的代码会抛出一个错误:

rows = myLayout[numSquares].r;

您可能想在 Layouts 类中创建一个方法,该方法返回其私有(private)数组 myLayouts,该数组可以进一步与索引一起使用。

而且,正如道文 7 指出的那样,该数组需要在某处进行初始化。

我正在用手机写这篇文章,所以不能输入太多:-P

关于java - 列表数组(Int,Int),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11979981/

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