Compare user input (char) with other char

How could I compare the input that I receiving from the user to a char? I will receive a letter from the user (That could be uppercase or lowercase) and then compare it whit the desired letter.

Example:

Scanner input = new Scanner(System.in);
char inlet;

System.out.println("Enter letter:");
inlet = input.next().atChar(0);

if(inlet == "A"){
System.out.println("Same letter");
}

How can I use toLoweCase() in my if statement?

Upvotes: 1

Views: 1360

Answers (2)

Giorgi Tsiklauri
Giorgi Tsiklauri

Reputation: 11138

char primitives are backed by the ASCII value holder integer numbers. So, if the question is

how to compare two char values?

then the answer would be to have a look on ASCII representations of char values, and to the fact, that every char can be represented as integer by casting it to int:

char c1 = 'a';
char c2 = 'c';
System.out.println((int)c1);

for example, 'a' is represented by corresponding integer ASCII value 97, 'A' - by 65, 'b' - by 98 and so on (pay attention on the capitalization).

So, you can easily write if (c1>c2){..//code here..} and corresponding ASCII integer numbers are to be compared respectively.

However, if the question is

how to change the case of a given char?

then the answer provided by @royalghost would work fine.

Upvotes: 1

royalghost
royalghost

Reputation: 2808

You can use either toUpperCase(char ch) or toLowerCase(char ch)1 to convert the user input and compare like below:

if ( Character.toLowerCase(inlet) == 'a' ){

}

OR

if ( Character.toUpperCase(inlet) == 'A' ){

}

Upvotes: 1

Related Questions