我目前正在學習 Java,并正在完成基于它的練習;但是,我在其中一項練習中遇到了一個特定問題。任務描述如下:
元素在位
給定一個包含數字 a 0 到 n2 - 1 的矩陣“nx n”,回傳正確位置的元素數。
例如給定一個 3x3 矩陣:
4 2 6 0 8 5 7 1 3每個數字的正確位置如下矩陣所示:
0 1 2 3 4 5 6 7 8將第一個矩陣作為輸入的軟體應該列印值 1,因為只有 5 在正確的位置。但是現在我已經將正確位置的元素數量更改為兩個它應該列印兩個但我得到 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);
uj5u.com熱心網友回復:
您已經在 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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/505262.html
上一篇:使用for回圈計算不同引陣列合
下一篇:在同一行列印多個物件
