2016-07-29 40 views
0

我想要生成一個乘法表,其中第一個EditText取實際數字,而第二個EditText取乘法表的實際範圍。當我運行該項目時,結果只有編號*範圍.. 任何人都可以幫助我在下面提到的循環或代碼或者,GridLayoutTableLayout而不是TextView顯示錶中的任何替代方法。在TextView中的顯示乘法表

protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_multiplication_table); 
    number = (EditText)findViewById(R.id.numberTable); 
    range = (EditText)findViewById(R.id.numberRange); 
    click = (Button)findViewById(R.id.click); 
    result = (TextView)findViewById(R.id.display); 
    final String x = range.getText().toString(); 
    click.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View view) { 
      int a = Integer.parseInt(number.getText().toString()); 
      int b = Integer.parseInt(range.getText().toString()); 



      for(int i = 1 ; i <= 10; i++) 
      { 
       for(int j = 1 ; j <= 10; j++) 
       { 
        int res = a * b; 
          result. setText(a +" * " + b + " = " + res); 

       } 





      } 
      return; 
     } 
    }); 

} 
} 
+0

什麼你是否指「實際數量」和「實際範圍」?也許你想要的最終結果的一個例子會有所幫助 –

+0

你可以給出EditText和預期結果的一些示例輸入嗎? –

+0

@ EthanWilliams-那麼..例如,如果我有一個實際的數字爲2 ..所需的範圍爲10 ..所以循環應該顯示..乘法表2 .. ..如.. 2 x 1 = 2至 2 x 10 = 20 –

回答

1

要爲每一行調用setText(),但setText()將重置TextView的文本,您可能需要使用append()代替

result.setText(""); 
int a = Integer.parseInt(number.getText().toString()); 
int b = Integer.parseInt(range.getText().toString()); 

for(int i = 1 ; i <= b; i++){  
    int res = a * i; 
    result.append(a +" * " + i + " = " + res + "\n");  
} 

或可能使用StringBuilder

int a = Integer.parseInt(number.getText().toString()); 
int b = Integer.parseInt(range.getText().toString()); 
StringBuilder builder = new StringBuilder(); 

for(int i = 1 ; i <= b; i++){  
    int res = a * i; 
    builder.append(a +" * " + i + " = " + res + "\n");  
} 

result.setText(builder.toString()) 
+0

@ lelloman-umm ..謝謝你的回答。但還是有一些問題..實際上應該是這樣 2×1 = 2 2 ×2 = 4 2×3 = 6 ..等等.. 但其等 數*範圍=值 範圍是不從1個 和其顯示相同的值,outuput開始如..實際數量=和期望範圍= 所以其顯示2×5 = 10 相同直到循環結束 –

+0

確定現在我明白了,我剛編輯答案,你應該只需要一個循環 – lelloman

+0

@ lelloman-非常感謝你的答案。它運作良好!你能否在另一個環境中幫我解決問題...正在嘗試開發一個具有基本功能的簡單計算器。如果在TextView中沒有任何輸入的情況下按下按鈕,我該如何禁用該按鈕。或者如果沒有輸入按下按鈕,我如何在TextView中顯示錯誤消息。任何形式的幫助將不勝感激。謝謝。 –