简体   繁体   中英

Loop printing twice java

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

}

}

MultiplicationTable 中的构造函数调用printTable方法,然后在 main 方法中再次调用它

You're calling printTable method twice:

  1. In constructor of MultiplicationTable class.

    public MultiplicationTable(int begin, int end){ printTable(begin,end); }

  2. 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.

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.

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