0

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("");
3
  • So what happens? Where is code of reading user input? Commented Apr 22, 2015 at 22:18
  • Scanner input = new Scanner(System.in); Commented Apr 22, 2015 at 22:20
  • String and char are for UTF-16 code units, one or two of which encode a Unicode codepoint. If you expect the subset of Unicode in common with ASCII, you have to check. Commented Apr 22, 2015 at 23:50

1 Answer 1

2

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

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

You should change

String str = input.next();

to

String str = input.nextLine();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.