0

I'm doing a java project on codeZinger where I need to take in a character value from the scanner and print the ASCII value. So far the code I have works for everything besides the "/n" character. In that case, codezinger returns the error "Exception in thread "main" java.lang.NullPointerException scanner".

I have attached my code below, I've tried everything and it won't work. I'm new to java from c++.

I tried even manually testing for /n using an if statement and that didn't work

public class Solution {
    public static void main(String[] args) {
        
        //creating input stream
        Scanner input = new Scanner(System.in);
        

        // allows character input from input stream
        char charIn = input.findInLine(".").charAt(0);
            if(input.equals("\\n"))
        {
            System.out.print("10");
        }
        // casts character to type int to get ascii value
        
         int intVal = (int)charIn;  
    
    
        System.out.print(intVal);
    }
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
JG98
  • 43
  • 5
  • I don't know what `findInLine` is supposed to do, but you can use `.next()` to scan characters – OneCricketeer Sep 01 '21 at 19:37
  • i tried using .next() and that doesn't work for either a space or the newline character. findInLine at least works for whitespace – JG98 Sep 01 '21 at 19:49

2 Answers2

0

input.equals() method in java never takes its parameter in apostrophe. Please go through this once : https://www.jquery-az.com/learn-java-equals-method-5-examples/

Moreover /n doesn't exist in java. If you have to print a line(Give a break) then you have to use System.out.println() , simply, and it will be printed in next line.

Also go through this for printing ASCII value https://www.javatpoint.com/how-to-print-ascii-value-in-java

  • `.equals` accepts all Objects, strings are objects. The problem is that a Scanner will never equal a String – OneCricketeer Sep 01 '21 at 19:36
  • ok i think i fixed equals(), but I don't understand how to take in the break and convert it to ascii. System.out.println() is for printing, but I need to take in the newline character from the input stream and convert it to ascii – JG98 Sep 01 '21 at 19:39
  • System.out.println() is for printing in new line, while System.out.print() is for printing in same line – Ishika Tiwari Sep 01 '21 at 19:45
  • yes but i need to print the ascii value of the newline (which is 10) – JG98 Sep 01 '21 at 19:46
  • https://stackoverflow.com/questions/39556301/how-to-print-ascii-value-of-an-int-in-java – Ishika Tiwari Sep 01 '21 at 19:58
0
int code;
while ((code = System.in.read()) != -1) {
    System.out.format("0x%02X ", code);
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35