|
// // File: /home/cs255001/demo/atoi/JavaInput_2.java // // Demo String = array of ASCII codes // public class JavaInput_2 { public static void main(String[] args) throws Exception { byte[] b = new byte[100]; int count; while ( true ) { System.out.print("Enter input: "); count = System.in.read(b); // Read from key board System.out.println("# characters read = " + count); for (int i = 0; i < count; i++) { System.out.println(b[i]); // System.out.println(String.format("%x", b[i]) ); // Print in Hex } System.out.println("\n"); /* ===================================================== Make a string using the byte array ===================================================== */ String s = new String(b); // Make a String s using byte array b System.out.println("String = " + s); System.out.println("ASCII codes (in decimal) for the string:"); for (int i = 0; i < s.length(); i++) { System.out.println( (int) s.charAt(i) ); } } } } |
This is the JavaInput_1.java program but extended with statements to:
(1) Create a String from the byte array: String s = new String(b); // Make a String s using byte array b (2) Show you the string: System.out.println("String = " + s); (3) And print the ASCII codes of the string in decimal numbers: for (int i = 0; i < s.length(); i++) { System.out.println( (int) s.charAt(i) ); } |
When you run this program using 12<ENTER> as input, you will see that the ASCII codes printed as the same:
cheung@aruba> java JavaInput_2 Enter input: 12 # characters read = 3 49 50 10 String = 12 ASCII codes (in decimal) for the string: 49 50 10 |
But you should realize that a string is just a series of ASCII codes (as you have seen in the example above).
|
(But I will only use the next( ) method in the Scanner class.
I will not use nextInt( ) that includes the conversion algorithm !!!)
Example on reading in a string:
// // File: /home/cs255001/demo/atoi/JavaInput_3.java // import java.util.Scanner; public class JavaInput_3 { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); String s = null; while ( true ) { System.out.print("Enter input: "); s = in.next( ); // Read a String from key board System.out.println("String = " + s); System.out.println(); System.out.println("ASCII codes (in decimal) for the string:"); for (int i = 0; i < s.length(); i++) { System.out.println( (int) s.charAt(i) ); } } } } |
Notice that the input string does not contain the NEWLINE character when you type 12<ENTER>:
cheung@aruba> java JavaInput_3 Enter input: 12 String = 12 ASCII codes (in decimal) for the string: 49 50 |
The ASCII code 10 is not present in the input.
(Because the next( ) method in the Scanner class does not consider the <ENTER> key press as part of the input line).
And this is the main reason why I use the Scanner class to read in an input string -- because we must not process the NEWLINE character when we convert !!