I want to print a letter instead of the index position using the indexOf(); method. The requirement is that: Inputs a second string from the user. Outputs the character after t
You can access a single character, or a letter, by caling método charAt()
from String
class
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);
}
So, running this code, assuming the input is StackOverFlow
, the output will be S
In your code I think doing the follow will work:
String letter = keyboard.next();
first = letter.charAt(0);
That might help!
So, what you want is print the first letter based on a letter the user has input? For example, for the word Keyboard, and user inputs letter 'a' the first letter might be 'R'. Is that it? – Guerino Rodella
Yes, I have to combine both the indexOf(): method and the charAt(): method – Hussain123
The idea is get next letter based on user input letter. I'm not sure I wunderstood it, but this is my shot
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
Hope that helps you.