java - 跟踪for循环中的输入
问题描述:
我必须接受三个整数的用户输入并比较这些整数。这是我迄今为止的代码,但我认为我可以通过for循环提高可读性,但是我不确定如何跟踪它们输入的所有内容以便比较它们。java - 跟踪for循环中的输入
System.out.print("Enter an integer: ");
int int1 = console.nextInt();
System.out.println();
System.out.print("Enter an integer: ");
int int2 = console.nextInt();
System.out.println();
System.out.print("Enter an integer: ");
int int3 = console.nextInt();
System.out.println();
编辑:我只是意识到我也可以做到以下几点,但是我通过循环跟踪的问题仍然存在。
System.out.print("Enter three integers: ");
int int1 = console.nextInt();
int int2 = console.nextInt();
int int3 = console.nextInt();
System.out.println();
答
int[] x = new int[3];
for(int i = 0; i<3; i++)
{
System.out.print("Enter an integer: ");
x[i] = console.nextInt();
System.out.println();
}
答
想到的是将输入存储在一个int数组的第一件事。例如:
int[] input = new int[3]; // Whatever size you want
for (int i = 0; i < input.length; i++) {
input[i] = console.nextInt();
System.out.println();
}
答
那么你可以通过使用数组来做到这一点。
int[] array = new int[3]; //this is an array
for (int i = 0; i < 3; i++) {
System.out.println("Enter an integer: \n");
array[i] = console.nextInt(); // here it will store the int values in array[i]
}
答
这么简单
System.out.print("Enter three integers: ");
int int1 = console.nextInt();
int int2 = console.nextInt();
int int3 = console.nextInt();
if (int1 == int2 && int2 == int3) System.out.println("Integers are the same");
else System.out.println("Integers are different");
保持答案在数组中。 – jalynn2