Java 用于循环保持值
这是一个非常基本的Java 用于循环保持值,java,for-loop,Java,For Loop,这是一个非常基本的for循环,我正试图设计它,但由于某些原因,它就是不起作用。我正在制作一个方法,用户可以输入3个测试分数(整数)。问题是,我需要将3个整数的值保存到一个变量中 public static int testScore() { //starts method int test1; int test2; int test3; int i; test1=0 for (i=1; i < 3; i++) { //starts for loop System.out.
for
循环,我正试图设计它,但由于某些原因,它就是不起作用。我正在制作一个方法,用户可以输入3个测试分数(整数)。问题是,我需要将3个整数的值保存到一个变量中
public static int testScore()
{ //starts method
int test1;
int test2;
int test3;
int i;
test1=0
for (i=1; i < 3; i++)
{ //starts for loop
System.out.print("\nPlease enter your test scores: ";
int test1=kb.nextInt();
} //end for loop
publicstaticinttestscore()
{//启动方法
int test1;
int test2;
int test3;
int i;
test1=0
对于(i=1;i<3;i++)
{//开始循环
System.out.print(“\n请输入您的考试分数:”;
int test1=kb.nextInt();
}//循环结束
忽略我可能遇到的任何语法错误(草稿),这会将我生成的3个值保存到test1、2和3,还是只保存test1,因为我有int test1=…谢谢。这就是为什么Java中有
int[]测试=新的int[3];
System.out.print(“\n请输入您的考试分数:”;
对于(i=0;i<3;i++){
test[i]=kb.nextInt();
}
您声明了两次test1
,一次在testScore
的范围内,一次在循环的范围内,这是不好的
另外请注意,数组在Java中是基于零的,您可能希望从0开始循环建议给变量一个有意义的名字,而不是<代码>测试<代码>。考虑把它改为<代码>值>代码>例如…< /p> < p>当我理解你的问题时,你想在变量中保存3个值(即你输入某处)。 我想你应该用一个新的
int[] tests = new int[3];
for (int i = 0; i < 3; i++) {
System.out.print("\nPlease enter your test scores: ");
tests[i] = kb.nextInt();
}
int[]测试=新的int[3];
对于(int i=0;i<3;i++){
System.out.print(“\n请输入您的考试分数:”);
tests[i]=kb.nextInt();
}
稍后您可以使用(动态数组),如果要保存未定义数量的值。将三个值写入同一个变量中三次,因此只有最后一个条目将保留。如果需要将更多值存储到单个变量中,请使用数组。此外,在循环中声明新变量,以便隐藏外部变量
int[] store = new int[3]
for (int i=0; i < 3; i++)
{ //starts for loop
System.out.print("\nPlease enter your test scores: ";
store[i]=kb.nextInt();
}
int[]存储=新int[3]
对于(int i=0;i<3;i++)
{//开始循环
System.out.print(“\n请输入您的考试分数:”;
store[i]=kb.nextInt();
}
使用数组而不是单个变量
Integer[] test_array = new Integer[3];
for (i=1; i < 3; i++)
{
System.out.print("\nPlease enter your test scores: ";
test_array[i] = kb.nextInt();
}
Integer[]测试_数组=新整数[3];
对于(i=1;i<3;i++)
{
System.out.print(“\n请输入您的考试分数:”;
test_数组[i]=kb.nextInt();
}
最好的方法是使用数组。但您仍然希望不使用数组:
System.out.print("\nPlease enter your test1 scores: ");
int test1=kb.nextInt();
System.out.print("\nPlease enter your test2 scores: ");
int test2=kb.nextInt();
System.out.print("\nPlease enter your test3 scores: ");
int test3=kb.nextInt();
但我强烈建议使用数组。
通过此链接学习阵列
您的循环每次迭代仅收集单个基准的输入 您有两个选择:
- 每次迭代为每个变量添加特殊情况(这是一场维护噩梦)
- 如前所述,使用适当大小的
,并使用驱动for循环的相同变量对其进行索引:数组
Array[i]=kb.nextInt()
int[]numbers=new int[3];
)。我相信这两个test1都是在testScore中声明的;绝不是作为类member@RichardTingle谢谢,我没注意到。
System.out.print("\nPlease enter your test1 scores: ");
int test1=kb.nextInt();
System.out.print("\nPlease enter your test2 scores: ");
int test2=kb.nextInt();
System.out.print("\nPlease enter your test3 scores: ");
int test3=kb.nextInt();