java - What's the problem with this code? -



java - What's the problem with this code? -

hi when run next code getting numberformatexception can help me out in debugging code.

import java.io.*; public class case1 { public static void main(string args[]) { char ch='y';int i=0; bufferedreader bf=new bufferedreader(new inputstreamreader(system.in)); system.out.println("ch before while:::"+ch); while(ch=='y'||ch=='y'){ try{ system.out.println("enter option"); i=integer.parseint(bf.readline()); system.out.println("after"+i); switch { case 1 ystem.out.println("1"); break; case 2 ystem.out.println("1"); break; } system.out.println("do u want continue(y/y"); ch=(char)bf.read(); system.out.println("ch after execution:::"+ch); } catch(numberformatexception e){e.printstacktrace();} catch(ioexception e){e.printstacktrace();} } }}

this problem have faced in daytoday work. bf.readline() gives empty string("") or character values [a-z].so precondition check

// allow integer parsed. string rawtext = br.readline().trim(); if ( isnumeric (rawtext) // returns false non numeric && rawtext.matches("-?\\d+?") // integers. )

updates :

// isnumeric implementation due credit craigtp

please refer brilliant logic

http://stackoverflow.com/questions/1102891/how-to-check-a-string-is-a-numeric-type-in-java

public static boolean isnumeric(string str) { numberformat formatter = numberformat.getinstance(); parseposition pos = new parseposition(0); formatter.parse(str, pos); homecoming str.length() == pos.getindex(); }

java

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -