Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

how to convert a string into integer and vice versa in java ?

$
0
0
import java.io.*;
import java.lang.*;

public class StringToInt{
public static void main(String[] args)throws IOException {

BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter an integer number: ");
String str = bf.readLine();
int i = Integer.parseInt(str);
System.out.println("String: " + str);
System.out.println("Integer: " + i);


}
}
Output :
Enter an integer number: 156
String: 156
Integer: 156
this is working good but if i give string as input am getting exceptions at run time as follows

Enter an integer number:
hello
Exception in thread "main" java.lang.NumberFormatException: For input string: "hello"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:449)
at java.lang.Integer.parseInt(Integer.java:499)
at StringToInt.main(StringToInt.java:10)
Java Result: 1


i need to accept strings also.
Thanks,Regards
-Bala sai krupa

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>