Button Button - 1 year ago 67
Java Question

[SOLVED]string index out of bounds exception, on an if else statement

The problem code is below, if you need the entire main method to help me, please ask. The code complies but does not run as expected. I am trying to make the code report back an exclamation mark if the number is out of bounds/larger than the last position of the source text, which is a string the user inputs, so the length cannot be predefined. Exception is 'StringIndexOutOfBoundsException'

TDLR num is an int, sourcetext is a string, both are inputs. Exception: when code should output an '!' instead.

import java.util.Scanner;

public class Temp {

public static void main(String[] args) {

Scanner sc;
int result, num= 0, end = -2, temp, infolost, count;
String word, sourcetext, answer, space= " ";
String sourcetext2, temp2;
char input, result2, chalost;
sc = new Scanner(System.in);

System.out.println("please enter sourcetext");
sourcetext = sc.nextLine(); // user inputs source text
sourcetext = sourcetext.toLowerCase(); // converts sourcetext into lowercase
System.out.print("Would you like to 1 encrypt, or 2 decrypt?");
answer = sc.next(); // user inputs choice

if (answer.equals("1")||(answer.equals("encrypt"))) {

System.out.println("Please enter at least one word to encrypt");
word = sc.next(); // user inputs one word

for (int i= 0; i < word.length(); i++) {
temp = sourcetext.indexOf(word.charAt(i)); // uses index to convert char positions int num
System.out.print(space + temp + space);
System.out.print(space + end);
else if (answer.equals("2")||(answer.equals("decrypt"))) {

System.out.println("Please enter digits, with one space between each. End with -2");
while (num > -2) {
num = sc.nextInt(); // num to decrypt
if (num > -2) {
result2 = sourcetext.charAt(num); // num converted into characters
} else if (num > sourcetext.length()) {
} else if (num<0) {

Answer Source

This could lead to an IndexOutOfBoundsException - since -1 is greater than -2 - but still out of bounds...

if (num > -2){      
    result2 = sourcetext.charAt(num); // num converted into characters

Edit: Unless the users input is -2 - the first if-Statement will always run... You probably need to re-work the logic there.

Edit2: If num is -1 sourcetext.charAt(num); leads to an IndexOutOfBounds. Do something like

if(num == -2) {
} else if (num >= 0 && num < sourcetext.lenght()) {
    // index ok
    result2 = sourcetext.charAt(num); // num converted into characters
} else {
    // index out of bounds
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download