Page 478 - Introduction to Programming with Java: A Problem Solving Approach
P. 478
444 Chapter 11 Type Details and Alternate Coding Mechanisms
/***************************************************************
*
PrintCharFromAscii.java
Dean & Dean
This illustrates manipulation of ASCII code values.
***************************************************************/
*
*
*
import java.util.*;
public class PrintCharFromAscii
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
int asciiValue; // user entered ASCII value
}
// end class PrintCharFromAscii
}
System.out.print("Enter an integer between 0 and 127: ");
asciiValue = stdIn.nextInt();
ch = (char) asciiValue; ⎫
⎬ Note the (char) cast operators.
nextCh = (char) (asciiValue + 1);⎭ System.out.println("Entered number: " + asciiValue); System.out.printAlnp("aAsgsociatPedDFcharEacntehr:a"n+ccehr); System.out.println("Next character: " + nextCh);
// end main
char ch;
char nextCh;
// the asciiValue’s associated character
// the character after ch in the ASCII table
Sample session:
Enter an integer between 0 and 127: 67
Entered number: 67
Associated character: C
Next character: D
Figure 11.7 Program illustrating use of cast to convert character codes into characters To get a better feeling for how this works, trace this code fragment:
1
int x, y;
x = 4;
y = ++x;
System.out.println(x + " " + y);
x = 4;
y = x++;
System.out.println(x + " " + y);
2
3
4
5
6
7
8
Here is the trace: