Reputation: 1191
I have no idea why my loop is printing twice. I have two separate classes that I have created and for whatever reason I cannot figure out why it's printing twice to the console. I am not sure if it is because I called it wrong in TableTest? Or if I had done something wrong elsewhere. I have run this both in my IDE and my Command Line and I'm still getting the same issue.
public class TableTest {
public static void main(String[] args){
int getBegin, getEnd;
System.out.println("Enter a number to start with: ");
Scanner input = new Scanner(System.in);
getBegin = input.nextInt();
while (getBegin < 0){
System.out.println("Please enter a number greater than 0.");
getBegin = input.nextInt();
}
System.out.println("Enter a number to end with: ");
getEnd = input.nextInt();
while (getEnd < 0 || getEnd < getBegin){
System.out.println("Please enter a number greater than 0. Or greater than your first input.");
getEnd = input.nextInt();
}
MultiplicationTable loop = new MultiplicationTable(getBegin, getEnd);
loop.printTable(getBegin, getEnd);
}
}
public class MultiplicationTable {
public MultiplicationTable(int begin, int end){
printTable(begin,end);
}
void printTable(int begin, int end){
System.out.println(String.format("%-10s %-10s %-10s", "Number", "Squared" , "Cubed"));
for (int i = begin; i <= end; ++i){
System.out.println(String.format("%-10s %-10s %-10s", i, i* i, i*i*i));
}
}
}
Upvotes: 0
Views: 414
Reputation: 2437
You're calling printTable
method twice:
In constructor of MultiplicationTable
class.
public MultiplicationTable(int begin, int end){ printTable(begin,end); }
In main
method and after geting instance of MultiplicationTable
class:
MultiplicationTable loop = new MultiplicationTable(getBegin, getEnd); loop.printTable(getBegin, getEnd);
So for these reasons, it executes the printTable
method twice.
Upvotes: 1
Reputation: 2090
your constructor in MultiplicationTable calls the printTable
method and then you call it again in the main method
Upvotes: 3