java - Print the type of object using Iterator -


i write method printing type of object not working properly. idea read input, insert them in arraylist , then, print types. provide input follow

42 3.1415 welcome hackerrank java tutorials! 

and eventually, output in reverse order such

string: welcome hackerrank java tutorials! double: 3.1415 int: 42 

it come in serial int, double , string. method provided below 1 solution. i'm trying solve bufferedreader now.

public static void printmethod ( ){           list<object> arr = new arraylist<object>();     scanner scan = new scanner(system.in);      int count = 0;       while (scan.hasnextline()) {          count++;           string line = scan.nextline();          if( count == 1 ){              try {                  integer v = integer.valueof(line.trim());                 arr.add(v);                 continue;             }               catch (numberformatexception nfe) {              }         }          if ( count == 2 ){              try {                  double d = double.valueof(line.trim());                 arr.add(d);                 continue;             }               catch (numberformatexception nfe) {              }         }         arr.add(line);                 }      (int = arr.size() - 1; >= 0; i--) {          object obj = arr.get(i);         class<?> type = obj.getclass();          string[] s = type.getname().tostring().split("\\.") ;          if ( s[s.length - 1 ].equals("integer") )             system.out.println( "int" + ": " +obj.tostring());          else              system.out.println(s[s.length - 1 ] + ": " +obj.tostring());          // system.out.println( );      }        }  

if understand question, need parse supported types. since question lists integer, double , string i'll show way might parse those. also, i'd use scanner. putting together, might like

list<object> arr = new arraylist<object>(); scanner scan = new scanner(system.in); while (scan.hasnextline()) {     string line = scan.nextline();     try {         integer v = integer.valueof(line.trim());         arr.add(v);         continue;     } catch (numberformatexception nfe) {     }     try {         double d = double.valueof(line.trim());         arr.add(d);         continue;     } catch (numberformatexception nfe) {     }     arr.add(line); } (int = arr.size() - 1; >= 0; i--) {     object obj = arr.get(i);     class<?> type = obj.getclass();     system.out.printf("%s: %s%n", type.getname(), obj.tostring()); } 

which ran (and received expected output) lke

42 3.1415 welcome hackerrank java tutorials! java.lang.string: welcome hackerrank java tutorials! java.lang.double: 3.1415 java.lang.integer: 42 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -