ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Java Program: How to Parse a String into Integer in Java Programming

Updated on June 19, 2013

Java Program: Parse String into Integer in Java Programming with a Sample Java Source Code

Parsing in Java is also a known practice by the Java Programmers. There are many reasons why a programmer parse a string into integer and for the sake of knowledge let us know how parsing takes place. Parsing usually use when extracting integers inside a string entered by the user. I first used it in a basic calculator program using joptionpane and jframe. The series of numbers and operators is entered by the user and the challenge is to solve it, identify the numbers and the operators inside the string and output the correct answer. However, in the following Java Source Code, we will just cover on how to use the parseInt() in Java. The program will compute the string entered by the user. So, to compute it, we will parse the string into integer. See the Java Source Code below.

Java Source Code on How to Parse a String into Integer

package parsing_in_java;

import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        String string_num1 = input.nextLine(); // string is use instead of int

        System.out.print("Enter another number: ");
        String string_num2 = input.nextLine();

        int integer_num1 = Integer.parseInt(string_num1);//this is how to parse string
        int integer_num2 = Integer.parseInt(string_num2);//another example on parsing

        System.out.println("The sum is: " + (integer_num1 + integer_num2));
            
    }

}

Sample Output:

Do you find this hub useful to you? Then, please rate it or leave a comment. Happy Programming!

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    Click to Rate This Article