[英]For some reason loop doesn't print out correct array values
打印陣列時,我在獲取正確輸出時遇到一些麻煩。 基本上我要做的是在main方法中設置一個數組,然后將該數組發送到另一個打印出這樣的東西的方法:
89 12 33 7 72 42 76 49
69 85 61 23
右邊是3個空格,在第8個數字后面開始新的打印行。 看起來很簡單,但我得到的是這樣的東西。
89
69 85 61 23
由於某種原因,它不會打印位置1和7之間的值。 這就是我所擁有的。
public class Test
{
public static void main (String [] args)
{
int [] myInches = {89,12,33,7,72,42,76,49,69,85,61,23};
printArrayValues(myInches);
}
public static void printArrayValues(int [] myInchesParam) {
for (int i = 0; i < 8; i++) {
System.out.print(" " + myInchesParam[i]);
System.out.println();
for (i = 8; i < 12; i++) {
System.out.print(" " + myInchesParam[i]);
}
}
}
}
我應該使用do-while嗎? 或者我仍然可以用for循環來做它我只是做錯了嗎?
有很多方法可以解決這個問題,但有一種方法可以使用模運算符來檢查是否已經打印了8個條目。 您向i添加1,因為您的數組是0索引。
for (int i = 0; i < myInchesParam.length; i++) {
System.out.print(myInchesParam[i] + " ");
if((i + 1) % 8 == 0) {
System.out.println();
}
}
編輯 :此方法的好處是它適用於任何數組長度。 其他一些建議則不會。
好吧,發生的事情是在循環中我從0開始,然后當它到達第二個循環時你將i設置為8,因此條件i <8不再有效。 最簡單的修復方法是不嵌套你的循環,但有
for (int i = 0; i < 8; i++) {
System.out.print(" " + myInchesParam[i]);
}
System.out.println();
for (i = 8; i < 12; i++) {
System.out.print(" " + myInchesParam[i]);
}
代替。 甚至可能更好
for (int i = 0; i < 12; i++) {
System.out.print(" " + myInchesParam[i]);
if(i==7) {
System.out.println();
}
}
問題是您在兩個嵌套for
循環中使用相同的變量。 這將導致外部數組在第一次迭代后停止,並僅打印第二行中的值。
如果i > 0 && i % 8 == 0
只需使用一個循環並打印一個新行:
public static void printArrayValues(int[] myInchesParam) {
for (int i = 0; i < myInchesParam.length; i++) {
if (i > 0 && i % 8 == 0)
System.out.println();
System.out.print(" " + myInchesParam[i]);
}
}
或者你可以使用i % 8 === 7
然后插入一個新行:
public static void printArrayValues(int[] myInchesParam) {
for (int i = 0; i < myInchesParam.length; i++) {
System.out.print(" " + myInchesParam[i]);
if (i % 8 == 7)
System.out.println();
}
}
但是在某些情況下,您可以使用最后一個解決方案獲得一個尾隨的新行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.