为什么只有最后一个输入是存储?
why just the last input is storage?
import java.util.Scanner;
public class error{
private static class punto{
int x, y;
}
private static class lados{
punto inicio = new punto();
public lados(punto inicio1){
inicio=inicio1;
}
public punto getInicio(){
return inicio;
}
public void setInicio(punto inicio){
this.inicio = inicio;
}
}
public static void main(String[]args){
Scanner leer = new Scanner(System.in);
punto inicio = new punto();
lados arreglo[] = new lados[100];
for(int i=0; i<3; i++){
inicio.x = leer.nextInt();
inicio.y = leer.nextInt();
arreglo[i] = new lados(inicio);
}
for(int i=0; i<3; i++){
System.out.println(arreglo[i].getInicio().x);
System.out.println(arreglo[i].getInicio().y);
}
}
}
我做错了什么?
我想在数组的索引中存储 ponits(x,y)
但只有最后一个输入存储在所有索引中......
也许还有其他方法可以做我想做的事,如果有人分享我会喜欢的。
输入:
1
2
3
4
5
6
输出:
5
6
5
6
5
6
预期输出:
1
2
3
4
5
6
您在创建的所有 lados
个实例中使用相同的 inicio
个实例:
for(int i=0; i<3; i++){
inicio.x = leer.nextInt();
inicio.y = leer.nextInt();
arreglo[i] = new lados(inicio);
}
如果您希望信息在每次迭代时不被覆盖,您应该为每个 lados 创建一个新的 punto 实例。
试试看:
for(int i=0; i<3; i++){
inicio = new punto()
inicio.x = leer.nextInt();
inicio.y = leer.nextInt();
arreglo[i] = new lados(inicio);
}
按照惯例,类 应以大写字母开头:Punto、Lados 等...
import java.util.Scanner;
public class error{
private static class punto{
int x, y;
}
private static class lados{
punto inicio = new punto();
public lados(punto inicio1){
inicio=inicio1;
}
public punto getInicio(){
return inicio;
}
public void setInicio(punto inicio){
this.inicio = inicio;
}
}
public static void main(String[]args){
Scanner leer = new Scanner(System.in);
punto inicio = new punto();
lados arreglo[] = new lados[100];
for(int i=0; i<3; i++){
inicio.x = leer.nextInt();
inicio.y = leer.nextInt();
arreglo[i] = new lados(inicio);
}
for(int i=0; i<3; i++){
System.out.println(arreglo[i].getInicio().x);
System.out.println(arreglo[i].getInicio().y);
}
}
}
我做错了什么? 我想在数组的索引中存储 ponits(x,y) 但只有最后一个输入存储在所有索引中...... 也许还有其他方法可以做我想做的事,如果有人分享我会喜欢的。
输入:
1
2
3
4
5
6
输出:
5
6
5
6
5
6
预期输出:
1
2
3
4
5
6
您在创建的所有 lados
个实例中使用相同的 inicio
个实例:
for(int i=0; i<3; i++){
inicio.x = leer.nextInt();
inicio.y = leer.nextInt();
arreglo[i] = new lados(inicio);
}
如果您希望信息在每次迭代时不被覆盖,您应该为每个 lados 创建一个新的 punto 实例。 试试看:
for(int i=0; i<3; i++){
inicio = new punto()
inicio.x = leer.nextInt();
inicio.y = leer.nextInt();
arreglo[i] = new lados(inicio);
}
按照惯例,类 应以大写字母开头:Punto、Lados 等...