我想在private void primos() {
int i, j;
boolean esPrimo;
int rInicial = 2;//Rango inicial
int rFinal = 200;//Rango final
for (i = rInicial; i <= rFinal; i++) {
esPrimo = true;
for (j = 2; j < i; j++) {
if (i % j == 0) {
esPrimo = false;
}
}
if (esPrimo) {
//No idea what to do here
}
}
}
中显示我之前定义的一系列数字中的素数,代码:
String
我不知道如何继续使用这些数字填充TextView
并将其显示在onCreate
中。我想我必须使用findViewById
进行投射并使用Array
,但是......我应该返回String
还是{{1}}?
答案 0 :(得分:2)
理想情况下,您需要将代码分成几个方法以便更好地进行组织。我的版本非常低效,只是设置代码。你应该看看Eratosthenes筛子的一些东西: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
private void primos() {
int i, j;
boolean esPrimo;
int rInicial = 2;//Rango inicial
int rFinal = 200;//Rango final
String build = "";
TextView myView = (TextView) findViewById(R.id.myid); //R.id.myid needs to be set by you
for (i = rInicial; i <= rFinal; i++) {
if (isPrime(i)){
build += i + " "; //however you want to display them
}
}
myView.setText(build);
}
public boolean isPrime(int n){
for (int i = 2; i < n; i++){
if (n % i == 0){
return false;
}
}
return true;
}
答案 1 :(得分:1)
声明String
以附加您拥有的所有答案并将其显示在TextView
private String primos() {
int i, j;
boolean esPrimo;
int rInicial = 2;//Rango inicial
int rFinal = 200;//Rango final
String primeSeries = "";
for (i = rInicial; i <= rFinal; i++) {
esPrimo = true;
for (j = 2; j < i; j++) {
if (i % j == 0) {
esPrimo = false;
}
}
if (esPrimo) {
primeSeries += i + ", ";
}
}
return primeSeries;
}
并且在调用primos()
函数时这样做
textView.setText(primos());