numberformatexception - Number format Exception in Java after inputting a string -
i have input character array , inputting number user. @ point getting numberformatexception code is:
public static void main(string[] args) throws ioexception { bufferedreader br = new bufferedreader(new inputstreamreader(system.in)); int n = integer.parseint(br.readline()); char c[] = new char[n]; (int = 0; < n; i++) { c[i] = (char) br.read(); } int k = integer.parseint(br.readline()); }
at last line it's giving me error.
you numberformatexception
if try convert non-valid integer string or empty string integer
.
string x = "abcd"; int y = integer.parseint(x);//this raises exception abcd not valid number
how handle it?
non-technical solution:
try smart man , enter numbers only.
technical solution:
try { string x = "abcd"; int y = integer.parseint(x); } catch(numberformatexcpetion ne) { system.out.println("numbers only!"); }
do not use br.read()
read characters. if enter them in seperate lines doesn't consider them.
using system.in.read()
instead.
int n = integer.parseint(br.readline()); char c[] = new char[n]; (int = 0; < n; i++) { char ch; { ch = (char) system.in.read(); } while (ch != '\n'); c[i] = ch; } int k = integer.parseint(br.readline());
Comments
Post a Comment