-5

I am trying to make it so that a random number will be generated and displayed and the user will input the number and hit the enter button. If the input text matches the random number generated, it will then do something. However, when I try to use if(message=random) an error appears saying that "An instance of type 'int' can not be assigned to a variable of type 'java.lang.String'. I do not know what to do or how to fix this.

My code is right here:

Public class MainActivity extends Activity {
/** Called when the activity is first created. */

int random = (int)Math.ceil(Math.random()*100);

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView number = (TextView)findViewById(R.ID.number);
    number.setText("" + random);

    }

public void enter(View view)
{
    EditText answer = (EditText) findViewById(R.id.answer);
    String message = answer.getText().toString();
    if(message=random)
4

3 に答える 3

3

Convert random to String using String.valueOf() method then use equals() method

if(message.equals(String.valueOf(random))
{

   // Do some stuff..
}
于 2013-02-21T02:59:16.237 に答える
2

There are actually two problems here:


Q1: How do you compare a String and an int in Java?

A: You don't. You either convert the String to an int, or the int to a String. Then you do the comparison with like types. (Java does not support comparison of primitive types and reference types ... apart from the case where the reference type is a boxed type of the appropriate kind; e.g. comparison of Integer and int works.)

In this case, it is more convenient to convert the int to a String because you don't need to deal with the case where the String is not a valid integer. Thus:

if (message.equals(String.valueOf(random)) ... 

But if you had wanted to test if random was (say) less than the number represented by message, that wouldn't work. You'd need to do something like this:

try {
    if (number < Integer.parseInt(message)) ...

} catch (NumberFormatException ex) {
    // do something ...
}

Q2: Why did you get that strange compilation error?

   "An instance of type 'int' can not be assigned to a variable 
    of type 'java.lang.String'"

A: Look at the statement:

   if(message=random)

You are using = where you intended to use ==. Your code tries to assign the value of random to message.

于 2013-02-21T03:05:41.507 に答える
1

Two problems here:

  1. you are assigning instead of comparing. You should use message == random
  2. You are comparing a string to an int. You should convert it using

    int intMessage = Integer.parseInt(answer.getText().toString());

    if(message == random){

system32 answer is probably safer because I am assuming here that your text will be a number.

于 2013-02-21T03:00:39.277 に答える