所以我有一门课程应该接受一个数字并获得主要因素。然后将这些因子存储在 ArrayList、Factors 中,并在最后打印出来。问题是它只适用于 4,当我做 16 时它会冻结。任何帮助都会很棒!
我的java类:
package com.frostbytedev.addsub;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Steven on 7/4/13.
*/
public class Factor extends Activity implements View.OnClickListener{
ArrayList<Integer> Factors = new ArrayList<Integer>();
ArrayList<Integer> toAdd = new ArrayList<Integer>();
ArrayList<Integer> toRemove = new ArrayList<Integer>();
int numToFactor;
TextView FactorResults;
EditText NumberInput;
Button bFactor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.factor);
initialize();
}
private void initialize() {
FactorResults = (TextView)findViewById(R.id.tvFactors);
NumberInput = (EditText)findViewById(R.id.etNumber);
bFactor = (Button)findViewById(R.id.bFactor);
bFactor.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.bFactor:
numToFactor = Integer.parseInt(NumberInput.getText().toString());
FactorNumber(numToFactor);
FindFactors(Factors);
PrintFactors(Factors);
}
}
private void PrintFactors(ArrayList<Integer> factors) {
//String joined = Factors.get(0)+", "+Factors.get(1);
String joined = TextUtils.join(", ", Factors);
FactorResults.setText(joined);
}
private void FactorNumber(int number) {
int multipliedFactors=1;
int i;
double middle = Math.ceil(number/2);
FactorResults.setText(String.valueOf(middle));
for(i=(int)middle;i>1;i--){
if(number%i==0){
Factors.add(i);
}
else
return;
}
for(i=0;i<Factors.size();i++){
multipliedFactors*=Factors.get(i);
}
if(multipliedFactors<number){
FactorNumber(number);
}
if(Factors.size()==0){
FactorResults.setText(number+" has no factors!");
}
}
public void FindFactors(ArrayList<Integer> factors){
int i;
for(i=0;i<factors.size();i++){
int y;
double middle;
middle = Math.ceil(factors.get(i)/2);
for(y=(int)middle;y>1;y--){
if(i%y==0){
toAdd.add(y);
toAdd.add(factors.get(i)/y);
toRemove.add(i);
RemoveExtras(toRemove);
AddNewFactors(toAdd);
FindFactors(Factors);
}
else
return;
}
}
}
private void AddNewFactors(ArrayList<Integer> toAdd) {
int i;
for(i=0;i<toAdd.size();i++){
Factors.add(toAdd.get(i));
}
}
private void RemoveExtras(ArrayList<Integer> toRemove) {
int i;
for(i=0;i<toRemove.size();i++){
Factors.remove(toRemove.get(i));
}
}
}