How to use parseInt() to get int from a string in Java

4 Answers

0 votes
package javaapplication1;

import java.io.IOException;

public class JavaApplication1 {

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

        String s = "13";
        
        int n = Integer.parseInt(s);
        
        System.out.println(n);
        System.out.println(++n);
        System.out.println(n + 12);
    }
}


/*
                   
run:

13
14
26
          
 */

 



answered Dec 18, 2016 by avibootz
0 votes
package javaapplication1;

import java.io.IOException;

public class JavaApplication1 {

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

        String s = "-12";
        
        int n = Integer.parseInt(s);
        
        System.out.println(n);
        System.out.println(++n);
        System.out.println(n + 12);
    }
}


/*
                   
run:

-12
-11
1
          
 */

 



answered Dec 18, 2016 by avibootz
0 votes
package javaapplication1;

import java.io.IOException;

public class JavaApplication1 {

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

        String s = "F35";
        
        int n = Integer.parseInt(s);
        
        System.out.println(n);
        System.out.println(++n);
        System.out.println(n + 12);
    }
}


/*
                   
run:

Exception in thread "main" java.lang.NumberFormatException: For input string: "F35"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
        ...
          
 */

 



answered Dec 18, 2016 by avibootz
0 votes
package javaapplication1;

import java.io.IOException;

public class JavaApplication1 {

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

        String s = "350X";
        
        int n = Integer.parseInt(s);
        
        System.out.println(n);
        System.out.println(++n);
        System.out.println(n + 12);
    }
}


/*
                   
run:

Exception in thread "main" java.lang.NumberFormatException: For input string: "350X"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
        ...
          
 */

 



answered Dec 18, 2016 by avibootz
...