首页 > 解决方案 > How do you make the application get to read the 1st letter of the 2nd word

问题描述

The question that my teacher gave me is : Create a Group Assignment that prompts the user for his or her name and then displays a group assignment. The group assignment depends on the FIRST LETTER OF THE STUDENT'S LAST NAME. Last names beginning with A through I are assigned to group 1, J through S are assigned to group 2 and T through Z are assigned to group 3.

example output: Enter you first and last name: Janus Smith You are assigned to group 2.

I don't know the code to get the first letter of the second word and if they are still code error please do fix it. Tnx.

    Scanner scan = new Scanner(System.in);
    String name;
    
    System.out.println("Enter your first and last name: ");
    name = scan.nextLine();
    
    
    for (int i = 0; i < name.length; i++){
        char ch = name.charAt(0);
        
        if(ch >= 'A' || ch >= 'a' || ch <= 'I' || ch <= 'i'){
            System.out.println("You are assigned to group 1.");
        }
        else if (ch >= 'J' || ch >= 'j' || ch <= 'S' || ch <= 's'){
            System.out.println("You are assigned to group 2.");
        }
        else if (ch >= 'T' || ch >= 't' || ch <= 'Z' || ch <= 'z'){
            System.out.println("You are assigned to group 3.");
        }
    }

标签: javastringchar

解决方案


You can split the whitespace-separated strings and extract the parts like this:

String name = "First Second";
String[] parts = name.split(" ");
// extract the second string from the 0-indexed array
String second = parts[1];
// extract the first character from the second string
char ch = second.charAt(0);

// no need to loop for a single name check

if(ch >= 'A' && ch <= 'I' || ch >= 'a' && ch <= 'i'){
    System.out.println("You are assigned to group 1.");
}
else if (ch >= 'J' && ch <= 'S' || ch >= 'j' && ch <= 's'){
    System.out.println("You are assigned to group 2.");
}
else if (ch >= 'T' && ch <= 'Z' || ch >= 't' && ch <= 'z'){
    System.out.println("You are assigned to group 3.");
}
else {
    System.out.println("Invalid input.");
}

推荐阅读