這是我的Android Java代碼。我不明白爲什麼它不像Java代碼那樣工作。它是素數的例子。假設我們想要找到1到5之間的素數。所以我期待結果2,3,5。但我只有結果5。在我的Java代碼中,我得到了正確的結果。我的意思是2,3,5。請幫我弄清楚這個問題。Android for loop不像java一樣工作
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prime);
Button btn = (Button)this.findViewById(R.id.click_btn);
btn.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
TextView resp = (TextView) findViewById(R.id.response);
// Get number from EditText
EditText startnumber = (EditText) findViewById(R.id.first_number);
EditText endnumber = (EditText) findViewById(R.id.second_number);
// get the Strings from the EditTexts
String number1 = startnumber.getText().toString();
String number2 = endnumber.getText().toString();
// Convert Strings to int
int x1number = Integer.parseInt(number1);
int x2number = Integer.parseInt(number2);
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
//resp.setText(str);
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
resp.setText(str + String.valueOf(i));
}
}
}
});
}
public static boolean isPrime(int n){
if(n <= 1) {
return false;
}
for(int i = 2; i <= n/2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
這是我的Java代碼。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package primenumberstwo;
import java.util.Scanner;
/**
*
* @author vubon
*/
public class PrimeNumberstwo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner s = new Scanner(System.in);
System.out.println("Enter your first number: ");
int start = s.nextInt();
System.out.println("Enter your second number: ");
int end = s.nextInt();
System.out.println("List of prime numbers bettween " + start + " and " + end);
for(int i = start; i <= end; i++){
if(isPrime(i)){
System.out.println(String.valueOf(i));
}
}
}
public static boolean isPrime(int n){
if(n <= 1) {
return false;
}
for(int i = 2; i <= n/2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
謝謝你的朋友。它正在工作。其實我正在學習Android SDK。 –
接受,如果你有解決方案。 – shobhan