gpt4 book ai didi

Java:从类创建一个新数组

转载 作者:太空宇宙 更新时间:2023-11-04 12:06:25 27 4
gpt4 key购买 nike

我有我的 Fila 类:

import java.util.Arrays;

public class Fila {

private int [] fila;

public Fila(int[] fila) {
this.fila = fila;
}

public Fila() {

}

public int[] getFila() {
return fila;
}

public void setFila(int[] fila) {
this.fila = fila;
}

@Override
public String toString() {
return "Fila{" +
"fila=" + Arrays.toString(fila) +
'}';
}
}

现在我想在我的 main 上创建一个新的 int 数组并插入用户输入的新值。我的主要自动提款机有以下代码:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {

Scanner teclado = new Scanner(System.in);
System.out.println("Fila dimension? ");
int n = teclado.nextInt();

Fila [] a = new Fila [n];
System.out.println("Dimension of Fila: "+a.length);
System.out.println("Place that you want to add? ");
int l = teclado.nextInt();

for (int i = l-1; i <= l-1; i++) {
System.out.println("Number? ");
a [i] = teclado.nextInt();
}
System.out.println(Arrays.toString(a));

}
}

但我这里有不兼容的类型:a [i] = teclado.nextInt();

我需要做什么?

最佳答案

在我看来,这就像你想要的:

public class Main {
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
System.out.println("Fila dimension? ");
int n = teclado.nextInt();

int [] a = new int [n];
System.out.println("Dimension of Fila: "+a.length);
System.out.println("Place that you want to add? ");
int l = teclado.nextInt();

for (int i = l-1; i <= l-1; i++) {
System.out.println("Number? ");
a [i] = teclado.nextInt();
}
System.out.println(Arrays.toString(a));

Fila fila = new Fila(a);
// Do something else with fila here...
}
}

当您编写 Fila a = new Fila[n] 时,您实际上是在创建一个 Fila 对象数组,而不是一个整数数组。

关于Java:从类创建一个新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40322462/

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