java - 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.");
}
}
解决方案
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.");
}
推荐阅读
- python - Snappy - 从像素到纬度的错误转换
- html - why img is not taking full width of parent?
- javascript - Reactjs将数据传递给父级不起作用
- ios - 优化顶点着色器
- azure-devops - 通过 REST API 获取工作项的父级
- reactjs - 在 AWS 中使用 S3 API 和 React 获取 ListBuckets 方法?
- javascript - 如何禁用单个 Monaco 编辑器语法规则
- c++ - CocoaPod - 在头文件中使用 C++ 时的 Podspec linting 错误
- django - 将预先存在的模型实例关联到新的父模型的最佳方法?
- jquery - 在媒体查询中禁用 CSS 动画