I am doing an activity in which you you write number in editview (usernumber) and then you get prime factors in textview next to it (primefactor). i used some strips of code for prime fators but I don't understand it much, so I will be thankful for any help. EDIT: Did some changes to code as suggested, but code still doesn't do anything:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;
public class activityone extends AppCompatActivity {
EditText usernumber;
TextView primefactor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
usernumber = (EditText) findViewById(R.id.number);
primefactor = (TextView) findViewById(R.id.primefactor);
usernumber.addTextChangedListener(prvoWatcher);
}
private final TextWatcher prvoWatcher = new TextWatcher() {
double f,
c;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.toString().equals("")){
f = Double.parseDouble(s.toString());
while (f%2==0)
{
primefactor.setText(2 + " ");
f /= 2;
}
int i;
for (i = 3; i <= Math.sqrt(f); i+= 2)
{
// While i divides f, print i and divide n
while (f%i == 0)
{
primefactor.setText(i + " ");
f /= i;
}
}
// This condition is to handle the case whien
// f is a prime number greater than 2
if (f > 2)
primefactor.setText(String.valueOf(f));
}
}
};
}
Thanks in advance.
Error is String.valueOf(int);
It expects a integer or float variable not the datatype.
primefactor.setText(String.valueOf(int));
That's not how it works, you can't just put a primitive type in there as an argument. Either replace int
by i
or by f
, depending on what you want to show.
So it looks like
primefactor.setText(String.valueOf(i));
or
primefactor.setText(String.valueOf(f));
EDIT: Of course, if you want to use the i
variable, you have to declare if before the for-loop, and not in it.
int i;
for (i = 3; i <= Math.sqrt(f); i+= 2)
{
// While i divides n, print i and divide n
while (f%i == 0)
{
primefactor.setText(i + " ");
f /= i;
}
}
primefactor.setText(String.valueOf(int));
什么是 int ?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.