-1

This is my homework assignment, I do not really know about Code, so, anyone can help me?

class Test {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        String string = scan.nextLine();
        int index = scan.nextInt();
        
        System.out.println(string.charAt(index));
    }
}
saeedata
  • 901
  • 6
  • 14
  • This is expected to happen if the index you provide is greater or equal to the length of the string. Compare [this test](https://ideone.com/PoYJLq) with [this one](https://ideone.com/4N1QGY) – Aaron Dec 12 '20 at 12:41
  • If you think one of the answeres were helpful, mark it as accepted the button below down-upvoting. – Aalexander Feb 14 '21 at 16:15

3 Answers3

0

Typo

Write instead of this

    int index = scan.nerxtInt();

that

    int index = scan.nextInt();

I would recommend debugging with System.out.println() when you get some of this errors. Just check what is inside of your variable. Is it the value which you expect.

Aalexander
  • 4,987
  • 3
  • 11
  • 34
0

you must check the index before use it, maybe it isn't valid in the rang of string:

if(index>=0 && index< string.length()){
        System.out.println(string.charAt(index));
}else{
        System.out.println("invalid index");
}
saeedata
  • 901
  • 6
  • 14
0

For another way of validating the string and given integer length, you can update your code as:

    Scanner scan = new Scanner(System.in);

    String string = "";
    try {
        string = scan.nextLine();
        int i = scan.nextInt();
        System.out.println(string.charAt(i));
    } catch (StringIndexOutOfBoundsException e) {
        System.out.printf("%d index is out of bound for given string %s%n",string.length(),string);
    }
artunc
  • 150
  • 1
  • 7