EditText numDisplay;
Button calculateNow;
int n=100;
int count=0;
List<Integer> primes = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numDisplay= (EditText)findViewById(R.id.editText1);
n= Integer.parseInt(numDisplay.toString());
calculateNow = (Button)findViewById(R.id.button1);
calculateNow.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
for (int i = 2; i < n; i++) {
boolean res = checkprime(primes, i);
if (res) {
count++;
primes.add(i);
}
}
numDisplay.setText( String.valueOf(count));
// writer.write("total prime number till " + n + " is " + count);
}});}
private static boolean checkprime(List<Integer> primes, int n) {
int fence = (int) Math.sqrt(n);
for (int prime : primes) {
if (n % prime == 0) {
return false;
}
if (prime >= fence)
break;
}
return true;
}
程序的输出必须打印从1到100的素数总数。
单击按钮时,我使用编辑文本显示素数的总数。
但是当我点击按钮时,我没有得到所需的输出。任何帮助表示赞赏。 感谢名单
答案 0 :(得分:0)
更新您的: -
public class AnimationActivity extends ActionBarActivity {
EditText numDisplay;
Button calculateNow;
private int n;
int count=0;
List<Integer> primes = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numDisplay= (EditText)findViewById(R.id.editText1);
calculateNow = (Button)findViewById(R.id.button1);
calculateNow.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
n= Integer.parseInt(numDisplay.getText().toString());
for (int i = 2; i < n; i++) {
boolean res = checkprime(primes, i);
if (res) {
count++;
primes.add(i);
}
}
numDisplay.setText(String.valueOf(count));
}
});}
private static boolean checkprime(List<Integer> primes, int n) {
int fence = (int) Math.sqrt(n);
for (int prime : primes) {
if (n % prime == 0) {
return false;
}
if (prime >= fence)
break;
}
return true;
}}