John Smth John Smth - 1 month ago 7
Java Question

java character position in a string

I was hoping that SO could help me with my issue. I have this code:

public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);

System.out.print("Enter a string:\t");
String word = scanner.nextLine();

System.out.print("Enter a character:\t");
String character = scanner.nextLine();

char charVar = 0;
if (character.length() > 1) {
System.err.println("Please input only one character.");
} else {
charVar = character.charAt(0);
}

int count = 0;
for (char x : word.toCharArray()) {
if (x == charVar) {
count++;
}
}

System.out.println("Character " + charVar + " appears " + count +
(count == 1 ? " time" : " times"));
}


So this code asks the user to enter a string, then it asks the user to enter a character, the program will then tell the user how many times that specific character appears. My problem is that I need to convert this code so it will still ask the user for the string, but wont ask for a character. It will instead ask for the user to enter a number. The program will then show what character is at that position in the string. Example: lets say they enter "string" and then 2 for the number, the program will display the character "r". So my question is basically if any one can give me an idea as how to accomplish this. Any help would be great.

Answer
public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);

        System.out.print("Enter a string:\t");
        String word = scanner.nextLine();

        System.out.print("Enter an integer:\t");
        int index = scanner.nextInt();

        System.out.println("Character at position " + index + ": " + word.charAt(index));
    }
Comments