繁体   English   中英

简单迭代程序中的Java方法类型错误

[英]Java method type error in simple iteration program

我一直在研究Downey的Think Java,并且对使用迭代来打印乘法表的一些代码非常了解。 我尝试自行复制程序,并收到“此处不允许的'void'类型”错误。 我以为可能是我犯的某个错误导致了错误,但我尝试编译Downey随书提供的代码,并收到了相同的编译时错误。 下面是代码:

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));
  }
}

如果有人可以帮助我了解这里发生的事情,那将是很好的。 提前致谢!

删除要打印的调用,只需调用该方法。

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

printTable方法不返回任何内容。 除了在main()中调用System.out.println ,还可以根据需要在printTable方法本身中添加print语句,然后仅从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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM