Java code to convert the individual character of a string into its ascii value


Steps

  1. Select Java form the categories and Java Application  from the projects, click Next.
  2. Set the Project name as  ascii  and set the Create Main Class, click Finish.
  3. Under the  project "ascii", you can see two files, double click the Source Packages,you can see a package by name " ascii " ,double click it you will find the Java Main Class File Ascii .java.
  4. Open this file, remove the existing code and  paste the following code.
------------------------------------------------Ascii.java-----------------------------------------------------------


package ascii;
import java.util.*;
/**
 *
 * @author ZISSAN
 */
public class Ascii {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // test is the input string
        String test="";
        // initialization of the Scanner class,handles input from user,can be found in the java.util.*; library.
        // we are creating object "in" from the scanner and telling java that this will be System input
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a string to convert it to ascii::");
        // next() is a method which  gets the next string of text that a user types on the keyboard
        test = in.nextLine();
        for ( int i = 0; i < test.length(); ++i ) {
       char c = test.charAt( i );// "c" holds the individual character of the string
       int j = (int) c;          // the value of "c" is parsed to integer type to get the required output
       System.out.println(j);   // "j" holds the ascii value of the individual character
       }
    }
}

-------------------------------------------------------output------------------------------------------------------------------
run:
Enter a string to convert it o binary::
abcd
97
98
99
100
BUILD SUCCESSFUL (total time: 9 seconds)

No comments:

Post a Comment