gpt4 book ai didi

java - Android for循环不像java那样工作

转载 作者:搜寻专家 更新时间:2023-11-01 09:50:38 24 4
gpt4 key购买 nike

这是我的 Android Java 代码。我不明白为什么它不像 java 代码那样工作。它是素数的例子。假设我们想找到 1 到 5 之间的素数。所以我期待结果 2, 3, 5 。但是我只得到了结果 5 。在我的 Java 代码中,我得到了正确的结果。我的意思是 2, 3, 5 。请帮我弄清楚这个问题。

    @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;
}
}

最佳答案

您在每次迭代中都覆盖了 TextView resp 的内容,这就是您只看到最后一个的原因。

尝试这样的事情:

    String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
String result = "";
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
result = result + " " + i;
}
}
if(!("".equalsIgnoreCase(result.trim()))){
resp.setText(str + result);
}

关于java - Android for循环不像java那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36402438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com