2017-05-04 60 views
0

我一直在努力通過Downey的Think Java,並且已經完全停留在使用迭代打印乘法表的一些代碼上。我試着自己複製這個程序,並收到了「這裏不允許的」'void'類型的錯誤。我認爲這可能是我犯的一個錯誤導致了錯誤,但我試着編譯了Downey提供的代碼,並且收到了相同的編譯時錯誤。下面是代碼:簡單迭代程序中的Java方法類型錯誤

public class Table { 

    public static void printRow(int n, int cols) { 
    int i = 1; 
    while (i <= cols) { 
    System.out.printf("%4d", n*i); 
    i = i + 1; 
} 
    System.out.println(); 
} 

public static void printTable(int rows) { 
    int i = 1; 
    while (i <= rows) { 
     printRow(i, rows); 
     i = i + 1; 
    } 
} 
public static void main(String[] args) { 
    System.out.print(printTable(5)); 
    } 
} 

如果有人能幫助我明白是怎麼回事,這將是巨大的。提前致謝!

+1

該print語句將永遠不會打印,因爲printTable()不會返回任何東西 –

+0

所以他的代碼是不正確的......我看到 –

回答

1

刪除要打印的電話並調用該方法。

public static void main(String[] args) { 
    printTable(5); 
} 
1

printTable方法不返回任何東西。如果需要,您可以在printTable方法本身中添加打印語句,而不要在main()中調用System.out.println,而只需從main()調用printTable方法。由於printRow已在打印輸出,因此我不確定要再次打印什麼。

public class Table { 

    public static void printRow(int n, int cols) { 
     int i = 1; 
     while (i <= cols) { 
      System.out.printf("%4d", n*i); 
      i = i + 1; 
     } 
     System.out.println(); 
    } 

    public static void printTable(int rows) { 
     int i = 1; 
     while (i <= rows) { 
      printRow(i, rows); 
      i = i + 1; 
     } 
    } 
    public static void main(String[] args) { 
     printTable(5); 
    } 
}