简体   繁体   中英

convert String to ASCII and ASCII to String

This is my code to convert String to ASCII and ASCII to String. I have problem when the user enter text with spaces the all texts didn't convert but if i wrote the text in program the text converted . This is my input "Java is easy"

String str = input.next();
//String str = "Java is easy";

char ch[] = str.toCharArray();
int num[] = new int[str.length()];

for (int i = 0; i < str.length(); i++) {
    System.out.print((int)ch[i] + " ");
    num[i] = (int)ch[i];
}
System.out.println("");
for (int j = 0; j < str.length(); j++) {
    System.out.print((char)num[j]);
}
System.out.println("");

Scanner.next() reads a single word, ie "Java".

Scanner.nextLine() reads an entire line, ie "Java is easy"

You should change

String str = input.next();

to

String str = input.nextLine();

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