Robotics C++ Physics II AP Physics B Electronics Java Astronomy Other Courses Summer Session  

Parsing

 

Introduction

Example

Exercises

 

Introduction

 

   These methods are declared in the classes (Integer, Double, etc) as static.

   An object, therefore, does not have to be created.

   You invoke the method by prefixing it with the name of the class.

   In each case, s is the string to be converted to the data type listed.

   As shown, the string is passed as an argument to the method.

   The value returned is either an integer, double, or float as listed.

     ♦  Double.parseInt (s)             //Note that the class is Integer, the method is parseInt

     ♦  Integer.parseInt (s)

   Data Types Review

Example

 

import javax.swing.*;

class MyClass

{

    public static void main(String[] args)

   {

      String ageIn = " ";         //initialize strings before using them

      int age = 0;                   //Java, unlike C++, initializes primitives to 0 - good practice in case in other languages that may not...

      int ageInFive = 0;

      ageIn = JOptionPane.showInputDialog ("Please enter your age as an integer");       //contents are, by default, of type String

      age = Integer.parseInt(ageIn);                                                                                        //parsing the age to be of type int

      ageInFive = age + 5;

      JOptionPane.showMessageDialog(null,"In 5 years you will be "+ageInFive,"Ages",JOptionPane.PLAIN_MESSAGE);

   }

}

 

 

Double.parseDouble (s)

    Same as above, with appropriate modifications

Float.parseFloat (s)

    Same as above, with appropriate modifications