0

I am attempting to write a program that when a user inputs a word, then an index, which causes the program to display the character at the given index, or gives error telling the user that the index given is too large . Whenever I run the code and put an index that is too large, I get an error message from the java instead. Any help is appreciated!

import java.util.Scanner;
public class scratch {
    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);
        System.out.printf("Enter a word:");
        String word = reader.next();

        Scanner letter = new Scanner (System.in);
        System.out.printf("Enter an index:");
        int index = letter.nextInt();

        char inputIndex = word.charAt(index);
        int length = word.length();
        if (index < length - 1 ) {
            System.out.printf("In word \"%s\", the letter at index"
                + " \"%2d\" is \'%c\'.\n"
                ,word, index, inputIndex );

        } else {
            System.out.printf("too big");   
        }
        reader.close();
        letter.close();
    }
}

Error message: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3 at java.base/java.lang.StringLatin1.charAt(Unknown Source) at java.base/java.lang.String.charAt(Unknown Source) at scratch.main(scratch.java:15)

gloob
  • 3
  • 3
  • have you looked at `String.fomat()`? – dehasi Sep 17 '18 at 12:05
  • What error message do you get? – deHaar Sep 17 '18 at 12:05
  • 2
    Consider using the same `Scanner` instance for all your reads, you don't need multiple ones. – Arnaud Sep 17 '18 at 12:06
  • use just one `Scanner` – Morteza Jalambadani Sep 17 '18 at 12:07
  • 1
    "I get an error message" - Error messages contain a lot of useful information to help you find out the cause of the problem. When you get an error message, then include the complete, exact error message in your question - don't just say "I get an error". That will make it easier to help you. – Jesper Sep 17 '18 at 12:07
  • Here is the error message that I receive: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3 at java.base/java.lang.StringLatin1.charAt(Unknown Source) at java.base/java.lang.String.charAt(Unknown Source) at scratch.main(scratch.java:15) – gloob Sep 17 '18 at 12:09
  • 3
    Never put more information into comments, always update your question instead. – GhostCat Sep 17 '18 at 12:10
  • Ah, okay. Sorry about that, obviously still super new to this. Thanks everyone for all the info! – gloob Sep 17 '18 at 12:13
  • Someone might close this as DUP to https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it – GhostCat Sep 17 '18 at 12:13
  • Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – OrdoFlammae Sep 17 '18 at 12:14

3 Answers3

6

You should call charAt after the check:

if (index < length ) {
    char inputIndex = word.charAt(index); // move this line here
    System.out.printf("In word \"%s\", the letter at index"
            + " \"%2d\" is \'%c\'.\n"
            ,word, index, inputIndex );

} else {
    System.out.printf("too big");   
}

The exception is caused by trying to get a character at an index that is too large. So you should try to get the character after you have ensured that the index is not too large, right?

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Additionnally, the condition should either be `index < length` or `index <= length - 1`, and there's no reason to create two `Scanner`s when a single one would work better (wouldn't fail if all the input is provided at once). – Aaron Sep 17 '18 at 12:11
  • That worked! Ah, that makes sense. Thank you for your help – gloob Sep 17 '18 at 12:12
  • Yes, that is true about scanners, but that has nothing to do with the issue. – OrdoFlammae Sep 17 '18 at 12:12
  • Yes, sorry about the extra scanner. My classmate added it, and I wasn't sure whether or not it shout be there. Thank you. – gloob Sep 17 '18 at 12:18
1

This is a perfect use for a try-catch block. Try accessing the index, catch the resulting exception if there is an error and print from there:

char inputIndex;
try {
    inputIndex = word.charAt(index);
} catch(IndexOutOfBoundsException e) {
    System.out.println("Out of bounds!");
}
Paul Benn
  • 1,911
  • 11
  • 26
  • No, it is not. You use try/catch in Java for situations that are *exceptional*. Failing on "string doesnt contain what I think it should" is not in that category. You simply add up front checks, to avoid the code throwing up in the first place. – GhostCat Sep 17 '18 at 12:12
  • This *is* an exceptional situation - you are trying to access an index which doesn't exist. `java.lang` even has [a defined Exception](https://docs.oracle.com/javase/8/docs/api/java/lang/IndexOutOfBoundsException.html) for this, as I'm sure you're aware. – Paul Benn Sep 17 '18 at 12:21
  • In Java, you *check* an index before you use it. Other languages follow a different mind set, but again, in Java you dont use try/catch for something like that. When an index out of bonds shows up, you *fix* the code, and prevent the exception from happening. This is mainly about the best practice to use here. There is also a NullPointerException. Does that mean you should throw these, or catch them?! – GhostCat Sep 17 '18 at 12:23
1

First of all - use one Scanner object. There is a correction in if condition as well. index should be less than or equal to length-1.

put char inputIndex = word.charAt(index); inside if statement.

Try this :

import java.util.*;



 public class Scratch { 

 public static void main(String[] args) {

    Scanner reader = new Scanner(System.in);
    System.out.printf("Enter a word:");
    String word = reader.next();

    //Scanner letter = new Scanner(System.in);
    System.out.printf("Enter an index:");
    int index = reader.nextInt();
    int length = word.length();
    if (index < length - 1) {
        char inputIndex = word.charAt(index);
        System.out.printf("In word \"%s\", the letter at index" + " \"%2d\" is \'%c\'.\n", word,
            index, inputIndex);

    } else {
        System.out.printf("too big");
    }
    reader.close();
    }
}

PS : Class name should be Scratch not scratch (java convention).

patidarsnju
  • 439
  • 5
  • 10