-3

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.

John Smth
  • 31
  • 2
  • 11

1 Answers1

1
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));
    }
  • Thank you for the answer. completely unrelated question, how big of an issue is it if you never close your Scanner in a program? – John Smth Oct 17 '16 at 23:11
  • In a short, simple example like the one here, which is only reading user input, it's not an issue, unless we were to read more input. If we were opening and reading files or other resources, of course, that's when it may become an issue (corrupting files, etc). However, there is no need to close it after using, the Java environment closes it automatically on program termination. – chickity china chinese chicken Oct 17 '16 at 23:22