P
P
progforgood2016-12-03 13:41:35
Java
progforgood, 2016-12-03 13:41:35

Why cast the result of the System.in.read(); function to Char?

class temp {   
  public static void main(String args[])   
    throws java.io.IOException { 
 
    char ch, answer = 'K'; 
 
    System.out.println("I'm thinking of a letter between A and Z."); 
    System.out.print("Can you guess it: "); 
 
    ch = (char) System.in.read(); // Зачем приводить к типу char если объявленная переменная ch и так char?
    
    if(ch == answer) System.out.println("** Right **"); 
    else System.out.println("...Sorry, you're wrong."); 
  }   
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
progforgood, 2016-12-03
@progforgood

In general, I can’t formulate an answer, but the vision of the situation is as follows:
After rephrasing the code a bit, we get the Unicode character number at the output .. so the compiler sees the character "K" as "75" (int) ..

class temp {   
  public static void main(String args[])   
    throws java.io.IOException { 
  
    int ch; char answer = 'K'; 
 
    System.out.println("I'm thinking of a letter between A and Z."); 
    System.out.print("Can you guess it: "); 
 
    ch = System.in.read(); // get a char 
    System.out.println(ch);
    /*if(ch == answer) System.out.println("** Right **"); 
    else System.out.println("...Sorry, you're wrong."); */
  }   
}

A
Alexey, 2016-12-03
@alsopub

It is not a variable that is cast to "char", but the result of the function execution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question