简体   繁体   中英

How can I convert the input value into Unicode and print it out?

I have to input Hello through Scanner and print it on the console with decimal numbers corresponding to each alphabet. The output values should be in a single line. I have to use 'char'. Help me!

import java.util.Scanner;

public class Cipher {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String var = "scan";
        
        char a = var.charAt(0);
        char b = var.charAt(1);
        char c = var.charAt(2);
        char d = var.charAt(3);
        char e = var.charAt(4);
        
        System.out.print(a);
        System.out.print(b);
        System.out.print(c);
        System.out.print(d);
        System.out.print(e);
    }
}

tl;dr

Always use code point integers, never char .

For a single line of output to console:

 System.out.println(
    Arrays.toString( "Hello👋".codePoints().toArray() )
 );
[72, 101, 108, 108, 111, 128075]

For separate lines:

for( int codePoint : "Hello👋".codePoints().toArray() )
{
    System.out.println( 
        "codePoint = " + codePoint + " = " 
        + Character.toString( codePoint ) 
    ) ;
}
codePoint = 72 = H
codePoint = 101 = e
codePoint = 108 = l
codePoint = 108 = l
codePoint = 111 = o
codePoint = 128075 = 👋

Code point integers, not char

Actually, the char type is obsolete, unable to represent even half of the 143,859 characters defined in Unicode . Instead, use code point integer numbers. This number is what you after anyways in your school assignment.

The String class offers a method codePoints to get a stream of the code point integers.

IntStream codePointStream = "Hello".codePoints() ;

You can turn that stream into a simple array of int primitive values.

int[] codePoints = codePointStream.toArray() ;

Loop the elements of that array. Print each number to the console. And print the character assigned to that code point number by calling Character.toString .

for( int codePoint : codePoints )
{
    System.out.println( "codePoint = " + codePoint + " = " + Character.toString( codePoint ) ) ; 
}

See this code run live at IdeOne .

codePoint = 72 = H
codePoint = 101 = e
codePoint = 108 = l
codePoint = 108 = l
codePoint = 111 = o

Now, make it more interesting by including a character that would fail if we were using the obsolete char type, character WAVING HAND SIGN at decimal code point 128,075: Hello

codePoint = 72 = H
codePoint = 101 = e
codePoint = 108 = l
codePoint = 108 = l
codePoint = 111 = o
codePoint = 128075 = 👋

Try this.

public static void main(String[] args) {
    new Scanner(System.in).next().chars().forEach(System.out::print);
}

input:

Hello

output:

72101108108111

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM