[英]How do I print one letter of a string that was input by the user in Java?
[英]How do I print a letter based on the index of the string?
我想使用 indexOf(); 打印一个字母而不是索引 position; 方法。 要求是: 输入来自用户的第二个字符串。 输出短语中字符串的第一个实例之后的字符。 如果字符串不在短语中,则输出一个声明。 例如输入为3,倒置,d。 output 应该是“e”,我得到了它的一部分工作,它输入一个 integer 而不是那个特定的 position 的字符串。 我将如何 output 一个字符串?
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);
}
}
您可以通过从String
class 调用 método charAt()
来访问单个字符或字母
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = keyboard.nextLine();
char firstLetter = phrase.charAt(0);
System.out.println("First Letter : " + firstLetter);
}
因此,运行此代码,假设输入为StackOverFlow
,则 output 将为S
在您的代码中,我认为执行以下操作会起作用:
String letter = keyboard.next();
first = letter.charAt(0);
这可能会有所帮助!
那么,您想要的是根据用户输入的字母打印第一个字母? 例如,对于单词键盘,用户输入字母“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
希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.