问题是 :
编写一个程序,读取用户 2 的全名,然后判断 2 是否是兄弟。
样品运行:
输入 2 个名称:
- First name: Ali Ibrahim Mohammed - Second name: Ahmad Ibrahim Mohammed
Ali and Ahmad are brothers
import java.util.*;
public class Test
{
static Scanner scan = new Scanner (System.in);
public static void main(String args[])
{
String name1 = ""; //the name1 without first name
String name2 = ""; //the name2 without first name
String firstname1="";//only the first name of name1
String firstname2="" ;//only the fist name of name2
String fname ="";
String lname ="";
String string, string2;
int space ;
int i =0;
int j=0;
System.out.println("Enter 2 names :");
while ( i<2 )
{
if (i==0)
System.out.println("- First name :");
else
System.out.println("- Second name :");
while (j==i)
{
string = scan.nextLine();
space= string.indexOf(" ");
fname = string.substring(0,space);
string2 = string.toLowerCase();
lname = string.substring(space);
string2 = lname.toLowerCase();
j++;
}
if(i==0){
firstname1=fname;
lname=name1;
}
else if(i==1){
firstname2=fname;
lname=name2;
}
i++;
}
if ( name1.equals(name2))
System.out.println(firstname1 + " and " + firstname2 + " are brothers ");
else
System.out.println(firstname1 + " and " + firstname2 + " are NOT brothers ");
}
}
我试着写我的代码,但他们总是兄弟,即使姓氏不一样!