gpt4 book ai didi

java - 我的输出仅显示数组对象中的最后一个输入

转载 作者:行者123 更新时间:2023-12-01 17:30:15 25 4
gpt4 key购买 nike

我正在练习如何使用数组对象,在下面的程序中我只允许创建偶数个对象,代码如下,请参阅下面的输出以了解错误

import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("the number of object you want to create for class X : ");
int choose = sc.nextInt();

X obj[] = new X[choose];

if(choose>=2 && choose%2==0)
{

int input;
for(int i=0;i<choose;i++)
{
System.out.print("insert the value for the "+ordinal(i+1)+" obj against odd: ");
input=sc.nextInt();
obj[i].odd=input;
}
}
else return;

for(int k=0;k<choose;k++)
{
System.out.println(obj[k].odd);
}
}
public static String ordinal(int i) {
int mod100 = i % 100;
int mod10 = i % 10;
if (mod10 == 1 && mod100 != 11) {
return i + "st";
} else if (mod10 == 2 && mod100 != 12) {
return i + "nd";
} else if (mod10 == 3 && mod100 != 13) {
return i + "rd";
} else {
return i + "th";
}
}

}

class X
{
static int odd;
}

输出显示如下

the number of object you want to create for class X : 4
insert the value for the 1st obj against odd: 5
insert the value for the 2nd obj against odd: 4
insert the value for the 3rd obj against odd: 3
insert the value for the 4th obj against odd: 2
2
2
2
2

虽然我期望我的输出是

the number of object you want to create for class X : 4
insert the value for the 1st obj against odd: 5
insert the value for the 2nd obj against odd: 4
insert the value for the 3rd obj against odd: 3
insert the value for the 4th obj against odd: 2
5
4
3
2

请告诉我需要对代码进行哪些更改,谢谢

最佳答案

您的类X的数据成员是static,这意味着它属于该类,而不是特定实例,并且您只需在每次迭代中覆盖它即可环形。相反,您应该将其作为实例成员(并且可能有一个构造函数来初始化它:

class X
{
int odd;
public X(int odd) {
this.odd = odd;
}
}

然后在循环的每次迭代中创建一个新实例:

for (int i = 0; i < choose; i++) {
System.out.print("insert the value for the " + ordinal(i + 1) + " obj against odd: ");
int input = sc.nextInt();
obj[i] = new X(input);
}

关于java - 我的输出仅显示数组对象中的最后一个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61136130/

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