1.

Write a program in java to accept a word and display the ascii code of each character of the word.Sample Input: BLUEJSample Output: B:- 66L:- 75U:- 84E:- 69J:- 73

Answer»

Required Answer:-

Given Question:

  • Write a program in Java to accept a word and display the ASCII CODE of each character of the word.

Approach:

This is an easy question. Check out the answer (given below).

import java.util.*;

public class ASCIIValue

{

public STATIC void main(String args[])

{

/*

* Written by: @AnindyaAdhikari.

*/

SCANNER sc= new Scanner(System.in);

System.out.print("Enter a word: ");

String word = sc.next();

int len = word.length();

for (int i = 0;i < len; i++)

{

char ch = word.charAt(i);

System.out.println("Character: " + ch);

System.out.println("ASCII Value: " + (int)ch + "\n");

}

sc.close();

}

}

How it's solved ?

Firstly, we will import Scanner class. Scanner class is used to take input from the user. It is present in utility package of Java. In the next step, I have created a class, main() METHOD. Now, I have declared objects of Scanner class. Using scanner class, take a word as input from the user. The next() method of Scanner class is used to input a word from the keyboard. Now, we will calculate the length of the word and then iterate a loop from i=0 to - 1 (Since, index value of a word starts with 0 and ends with length - 1th index). Now, we will extract each characters starting from index 0. We can extract characters from the word by using a method charAt(<IndexValue>). I have STORED the character in a variable named ch. Now, we will find the ASCII value of the character by explicit type casting.

Variable Description:

  1. Word (String) :- Used to store the entered word.
  2. Len (int) :- Used to store the length of the entered word.
  3. i (int) :- Loop variable.
  4. ch (char) :- Extract each characters of word and store.

Output is attached.



Discussion

No Comment Found