-5

So I'm a beginner in Java right now and I've been playing around with strings a bit. Now I'd like to give the user an input choice "Enter a or b: " and give an output based on either "a" or "b"

The Code:

int a = 18;
int b = 22;

Scanner user_input = new Scanner (System.in);

String first_name;
System.out.println("Enter your first name: ");
first_name = user_input.next();

String last_name;
System.out.println("Enter your last name: ");
last_name = user_input.next();

String full_name;
full_name = first_name + " " + last_name;
System.out.println("You are: " + full_name);

String age;
System.out.println("Enter a or b: ");
age = user_input.next();

String age_a;
System.out.println("Your age is 18");
age = user_input(a);

I was also thinking maybe a function could be used like:

if(user_input = a)
{
   System.out.println("Your age is 18.");
}
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
Bogdan Lazar
  • 111
  • 3
  • 15
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Alex Salauyou Apr 17 '15 at 12:57
  • The most duplicated Java question ever – Alex Salauyou Apr 17 '15 at 12:57
  • Yea, well if you're a complete beginner and don't even know what to search for, it might get a bit difficult to find anything. I have been looking for a solution for 30min, before posting. So yea, -1 vote me for wanting to learn please.. – Bogdan Lazar Apr 17 '15 at 13:02

2 Answers2

3

Once you have age you must check the value, but as it is a String you MUST use String.equals()

if (age.equals("a"))
   System.out.println("Your age is 18");
else 
   System.out.println("Your age is 22");

If you want to check the answer is ONLY a or b use a while loop to repeat the question until answer is the desired:

String age;
while (!age.equals("a") || !age.equals("b")) {
    // ask for age
}
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
2

You can use an if with "string".equals("other_string") to compare them:

int a = 18;
int b = 22;

Scanner user_input = new Scanner (System.in);

System.out.println("Enter your first name: ");
String first_name = user_input.next();

System.out.println("Enter your last name: ");
String last_name = user_input.next();

String full_name = first_name + " " + last_name;
System.out.println("You are: " + full_name);

System.out.println("Enter a or b: ");
String ageChoice = user_input.next();

String age = null;
if(ageChoice.equals("a")){
    age = String.valueOf(a);
}
else if(ageChoice.equals("b")){
    age = String.valueOf(b);
}
System.out.println("Your age is: " + age);
Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135