简体   繁体   中英

Why am I getting a java.lang.StringIndexOutOfBoundsException error when I run?

I'm learning Java, and we got a project to make a program translating text into ASCII, and back.

My main method so far is

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        char decisionOne;
        System.out.println("Are we making a new message or decrypting an old one?");
        decisionOne = s.nextLine().charAt(0);
        switch(decisionOne) {
        case 'd':
            decrypt();
            System.exit(0);
            break;
        case 'D':
            decrypt();
            System.exit(0);
            break;
        case 'E':
            encrypt();
            System.exit(0);
            break;
        case 'e':
            encrypt();
            System.exit(0);
            break;
        }
        while (!(decisionOne == 'd') && !(decisionOne == 'D') && !(decisionOne == 'e') && !(decisionOne == 'E')) {
            System.out.println("Hey! Choose one of them.");
            decisionOne = s.nextLine().charAt(0);
            switch(decisionOne) {
            case 'd':
                decrypt();
                System.exit(0);
                break;
            case 'D':
                decrypt();
                System.exit(0);
                break;
            case 'E':
                encrypt();
                System.exit(0);
                break;
            case 'e':
                encrypt();
                System.exit(0);
                break;
            }
        }
        

    }

and my method for encrypting into ASCII is

        Scanner s = new Scanner(System.in);
        System.out.println("What is your message?");
        String message = s.nextLine();
        char m;
        int length = message.length();
        int tracker = 0;
        int ascii;
        while (length >= 0 ) {
            
            m = message.charAt(tracker);
            length--;
            ascii = (int)m;
            System.out.print(ascii + " ");
            tracker ++;
        }
        
    }

I've looked around at other questions, but none of them seem to answer what's happening here. When I run, I get the right output, so if I entered

11

I would get

49 49 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2

What could I do to fix this?

You want while (length > 0) or while (tracker < length)

Or you can just do for (Character m: message.toCharArray()) and forego the length, tracker, and charAt method

I put this in your encrypt method and..

m = message.charAt(tracker);
        System.out.print(length + " ");
        length--;
        ascii = (int)m;
        System.out.print(ascii + " ");
        tracker ++;
        System.out.print(length + " "+tracker+" ");

output i got is thisss...

2 49 1 1 1 49 0 2

you see your tracker=2 in the last which is out of bound for your message string that's why you are getting an exception either you can handle the exception or improve your code... personal experience -- use for loop if you are a beginner it will give you more clarity on how the code works

Change your code in encrypt method from while(length >= 0) to while(length - 1 >= 0) . Also close the scanner object after using it as it would result in memory leak.

The length() method return the length of the string, (eg) String message = "Hello"; length = message.length(); String message = "Hello"; length = message.length(); length would be equal to 5. But while using it in the while loop you have to use message.length() - 1 because in Java indexing starts at 0 rather than at 1.

I refactored your encypt method and main method and also I feel there is no need to use switch statements. Replace them with if else statements to reduce redundant code.

If you find this solution useful, kindly upvote the solution Thank you.

public static void encrypt() {
        Scanner s = new Scanner(System.in);
            System.out.println("What is your message?");
            String message = s.nextLine();
            char m;
            int length = message.length();
            int tracker = 0;
            int ascii;
            while (length - 1 >= 0 ) {
                
                m = message.charAt(tracker);
                length--;
                ascii = (int)m;
                System.out.print(ascii + " ");
                tracker++;
            }
            s.close();
        }

public static void main(String[] args) {
            Scanner s = new Scanner(System.in);
            char decisionOne;
            System.out.println("Are we making a new message [e (or) E] or decrypting an old one [d (or) D] ?");
            decisionOne = s.nextLine().charAt(0);
            if (decisionOne == 'd' || decisionOne == 'D') {
                decrypt();
                System.exit(0);
            }
            else if (decisionOne == 'e' || decisionOne == 'E') {
                encrypt();
                System.exit(0);
            }

            while (!(decisionOne == 'd') && !(decisionOne == 'D') && !(decisionOne == 'e') && !(decisionOne == 'E')) {
                System.out.println("Hey! Choose one of them.");
                decisionOne = s.nextLine().charAt(0);
                if (decisionOne == 'd' || decisionOne == 'D') {
                    decrypt();
                    System.exit(0);
                }
                else if (decisionOne == 'e' || decisionOne == 'E') {
                    encrypt();
                    System.exit(0);
                }
            }
            s.close();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM