java - The operator < is undefined for the argument type(s) String, int -
i'm having problem when trying run program. program supposed receive number , compare int. understand program thinks i'm trying compare string int , not happy it. can do?
import java.util.scanner; public class c { public static void main(string args[]) { scanner input = new scanner (system.in); string age = input.nextline(); if (age < 50){ system.out.println("you young"); }else{ system.out.println("you old"); } } }
you cannot compare string
int
using numerical comparison-operator. §15.20.1 of java language specification describes seeing:
the type of each of operands of numerical comparison operator must type convertible (§5.1.8) primitive numeric type, or compile-time error occurs.
since string
not convertible primitive numeric-type, cannot compare against integer. therefore have 2 options:
you can convert
string
int
usinginteger#parseint
:int age = integer.parseint(agestring);
but in case, since reading in input, better bypass whole
parseint
bit , read inint
directly:int age = input.nextint();
keep in mind though still have deal possibility of invalid input.
Comments
Post a Comment