Sergio Garcia Sergio Garcia - 6 months ago 18
Android Question

Operator '>' cannot be aplieed to 'java.lang.string'

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


final TextView label1=(TextView)findViewById(R.id.label1);
final TextView label2=(TextView)findViewById(R.id.label2);
final EditText introducir=(EditText)findViewById(R.id.introducir);
Button probar=(Button)findViewById(R.id.probar);

final Random dado=new Random();

final String numTxt="";

probar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

int cont=0;
cont=cont+1;
int num=5/*dado.nextInt(100)+1*/;

num=Integer.parseInt(numTxt);

if (introducir.getText().toString()==numTxt){

label1.setText("¡¡¡HAS ACERTADO!!!");
label2.setText("");


}
if (introducir.getText().toString()>numTxt){
label1.setText("¿"+num+"? ¡Uy! El número que he pensado es mayor");
label2.setText("");
}


}
});


The error is in exactly in this line:

if (introducir.getText().toString()>numTxt)

I do'nt unnderdtand the error because i have made the cast, so can somebody help me? please.
Thanks.

Answer

You can not compare String with ">" so the solution that I give to you is:

Since you are gettint it from an EditText the result will be a String so you have two options :

1.- Use Integer.valueOf()

try{

  int val = Integer.valueOf(introducir.getText().toString())

}catch(NumberFormatException e){

 Toast.makeText(this, "El valor no es un entero",
 Toast.LENGTH_LONG).show();

}

2.- Use Integer.parseInt()

try{

  int val = Integer.parseInt(introducir.getText().toString())

}catch(NumberFormatException e){

 Toast.makeText(this, "El valor no es un entero",
 Toast.LENGTH_LONG).show();

}

then you can use if(val>num){}

Hope it was clear.