java - 如何根据字符串的索引打印一个字母?
问题描述
我想使用 indexOf(); 打印一个字母而不是索引位置 方法。要求是: 输入来自用户的第二个字符串。输出短语中字符串的第一个实例之后的字符。如果字符串不在短语中,则输出一个声明。例如输入为3,倒置,d。输出应该是“e”,我得到了它的一部分,它输入一个整数而不是那个特定位置的字符串。我将如何输出一个字符串?
else if (option == 3){
int first = 0;
String letter = keyboard.next();
first = phrase.indexOf(letter,1);
if (first == -1){
System.out.print("'"+letter+"' is not in '"+phrase+"'");
}
else {
System.out.print(first + 1);
}
}
解决方案
基于这些评论
那么,您想要的是根据用户输入的字母打印第一个字母?例如,对于单词键盘,用户输入字母“a”,第一个字母可能是“R”。是这样吗?——盖里诺·罗德拉
是的,我必须结合 indexOf(): 方法和 charAt(): 方法 – Hussain123
这个想法是根据用户输入的字母获取下一个字母。我不确定我是否理解它,但这是我的镜头
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = "keyboard";
String userInput = keyboard.nextLine();
boolean notContainsInputValue = !phrase.contains(userInput);
if (notContainsInputValue) {
System.out.println("The input value doesn't exists");
return;
}
char firstLetter = userInput.charAt(0);
int desiredIndex = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == firstLetter) {
desiredIndex = i;
break;
}
}
System.out.println("The index for your input letter is: " + desiredIndex);
System.out.println("Next letter based on input value is: " + phrase.charAt(desiredIndex + 1));
}
输出
The index for your input letter is: 5
Next letter based on input value is: r
希望对您有所帮助。
推荐阅读
- c# - 可观察集合
替换以及如何让 DataModel 触发属性已更改 - c++ - 具有不同参数的重载函数
- xcode - Xcode Build Error Prefix.pch Defines.h file not found
- tcl - 使用 TCL 剥离部分 URI 路径
- python - Creating a json parsing function with Python
- python - How to get Chrome Native Messaging example to work with Python script on Mac
- python - 用多个元素交换 Python 中的元组列表
- kubernetes - 其他主机无法访问 Pod
- html - 如何在 Angular 中使用模板引用动态呈现 ng-template
- javascript - How to inject promise array inside observable array