2016-02-06 214 views
0

我不知道爲什麼我的循環打印兩次。我有兩個獨立的類,我已經創建了,無論什麼原因,我不知道爲什麼它打印兩次到控制檯。我不確定是不是因爲我在TableTest中稱它爲錯誤?或者如果我在其他地方做錯了什麼。我已經在我的IDE和我的命令行中運行了這個功能,但仍然遇到同樣的問題。循環打印兩次java

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

} 

} 

回答

3

您在乘法表構造函數調用printTable方法,然後你在main方法

+0

啊!謝謝你,我很困惑爲什麼會這樣。 – Sailanarmo

1

再次調用它你叫printTable方法兩次:

MultiplicationTable類的構造函數。

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

2.main方法和歌廳MultiplicationTable類的實例後:

MultiplicationTable loop = new MultiplicationTable(getBegin, getEnd); 
loop.printTable(getBegin, getEnd); 

因此,對於這個原因,它執行printTable方法的2倍