[英]How can i print total number of elements in the correct position?
我目前正在学习Java,并在此基础上完成练习; 但是,我在其中一项练习中遇到了一个特定问题。 任务描述如下:
position 中的元素
给定一个包含数字 a 0 到 n2 - 1 的矩阵“nxn”,返回正确 position 中的元素数。
例如给定一个 3x3 矩阵:
4 2 6 0 8 5 7 1 3
每个数字的正确 position 如以下矩阵所示:
0 1 2 3 4 5 6 7 8
将第一个矩阵作为输入的软件应该打印值 1,因为只有 5 在正确的 position 中。但是现在我已经将正确位置的元素数量更改为两个它应该打印两个但我得到 1 1 im不知道如何添加那些 1 和 1 以获得两个。
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" to the terminal window.
System.out.println("Hello, World");
int[] arr = {4,2,6,0,8,5,7,1,8};
for(int i = 0; i < arr.length ; i++) {
int count = 0;
if (arr[i] == i) {
count++;
System.out.println(+ count);
您已经在 for 循环内声明了 count 变量,并在循环内打印了结果。 这是执行此操作的正确代码-
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" to the terminal window.
System.out.println("Hello, World");
int[] arr = {4,2,6,0,8,5,7,1,8};
int count = 0;
for(int i = 0; i < arr.length ; i++) {
if (arr[i] == i) {
count++;
}
}
System.out.println(count);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.