I have been working my way through Think Java by Downey and have gotten quite stuck with a bit of code that uses iteration to print a multiplication table. I tried replicating the program on my own and received a "'void' type not allowed here" error. I thought it might have been some mistake I had made that had caused the error, but I tried compiling the code Downey had provided with the book and received the same compile-time error. Below is the code:
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));
}
}
If anyone can help me understand what's going on here that would be great. Thanks in advance!
Remove the call to print and just call the method.
public static void main(String[] args) {
printTable(5);
}
printTable
method does not return anything. Instead of calling System.out.println
in main()
, you can add the print statement in printTable
method itself if needed and then just call the printTable
method from main()
. I am not sure what you want to print again as the printRow
is already printing the output.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.