How do I run an if statement with a char input?
For example I want the user to input either A, B, or C. I then want my method to execute based on which of those letters were entered. What do I put in the if statement to get it to work? I understand the Scanner object and all that basic stuff. I just want to know what is the proper syntax to get an if statement to work with a single char if possible. Thank you.
If I’m not mistaken, you’re using Java, right? (just to make sure I didn’t talk different ‘language’) since you have the Scanner object.
After you import the Scanner object, we then define a variable to store the user input,
since you only want to ‘catch’ one character, I suggest "CHAR" is the best variablel type since it’s small
then we store the user’s response on that variable. Therefore, we can do you intend to do.
=================================================
import java.lang.* ; //for the ‘equalsIgnoreCase’ comparison
import java.util.Scanner.*;
public class void ClassName(){
char c;
Scanner input= new Scanner();
char = input.nextChar();
//you can use either ’switch…case’ or ‘if..else’
//let’s just if
if(c.equalsIgnoreCase(’A'))
{
//some codes
}
else if(c.equalsIgnoreCase(’A'))
{
//some codes
}
else
{
//some codes
}
}
==================================================
hope it helps
regards
Ahmad Nasikun
ahmadnasikun.wordpress.com
nasikun_jpr@yahoo.com
April 7th, 2011 at 10:38 am
Presuming that your using java.util.Scanner, you could either:
String s = scanner.nextLine();
switch(s.charAt(0)) {
case ‘A’:
case ‘B’:
case ‘C’:
}
OR
if(s.equals("A")) {
}…..
References :
April 7th, 2011 at 10:54 am
String input = "A";
if ( input.equals("A") ) {
….. // if A do this
} else if ( input.equals("B") ) {
….. // if B do this
} else {
….. // if C do this
}
References :
April 7th, 2011 at 11:24 am
If I’m not mistaken, you’re using Java, right? (just to make sure I didn’t talk different ‘language’) since you have the Scanner object.
After you import the Scanner object, we then define a variable to store the user input,
since you only want to ‘catch’ one character, I suggest "CHAR" is the best variablel type since it’s small
then we store the user’s response on that variable. Therefore, we can do you intend to do.
=================================================
import java.lang.* ; //for the ‘equalsIgnoreCase’ comparison
import java.util.Scanner.*;
public class void ClassName(){
char c;
Scanner input= new Scanner();
char = input.nextChar();
//you can use either ’switch…case’ or ‘if..else’
//let’s just if
if(c.equalsIgnoreCase(’A'))
{
//some codes
}
else if(c.equalsIgnoreCase(’A'))
{
//some codes
}
else
{
//some codes
}
}
==================================================
hope it helps
regards
Ahmad Nasikun
ahmadnasikun.wordpress.com
nasikun_jpr@yahoo.com
References :