输入字符串选择

时间:2015-04-17 12:47:33

标签: java string

所以我现在是Java的初学者,我一直在玩字符串。现在,我想为用户提供输入选项"Enter a or b: ",并根据"a""b"提供输出

守则:

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);

我也在想也许可以使用一个函数,如:

if(user_input = a)
{
   System.out.println("Your age is 18.");
}

2 个答案:

答案 0 :(得分:3)

一旦你age,你必须检查价值,但因为它是String必须使用String.equals()

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

如果您想检查答案是 a还是b,请使用while循环重复此问题,直到找到答案:

String age;
while (!age.equals("a") || !age.equals("b")) {
    // ask for age
}

答案 1 :(得分:2)

您可以使用带有"string".equals("other_string")的if来比较它们:

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);