I need to get the ASCII value of each character entered. I have char and whitespace but can not seem to get a value for "next line" / enter.

I thought to use an if statement saying that if(letter == '\n') (ascii = 10) but it 1. does not work and 2. it is forcing the value manually and I am trying to figure out how to get it read and assigned automatically.

 Scanner scan = new Scanner(System.in); char letter = scan.nextLine().charAt(0); int ascii = (int) letter; System.out.println(ascii); scan.close(); 
2

2 Answers

The scanner eats the end-of-line after detecting it. You get the characters input up to, but including, the end-of-line.

Also, you should not use char to track single letters. As a simple 16-bit value, it can only represent characters from the Basic Plane of Unicode, less than half the 137,000 characters defined in Unicode.

Use the integer-based methods such as String::codePointAt and String::codePoints.

The ASCII value of the new character is 10 (0x0A). The value of carriage return is 13 (0x0D).

public class HelloWorld { public static void main(String[] args) { String hello = "Hello World!\n"; System.out.print(hello); int letter = (int)hello.charAt(hello.length()-1); System.out.println(letter); } } 
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy