简体   繁体   English

为什么我在运行时收到 java.lang.StringIndexOutOfBoundsException 错误?

[英]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.我正在学习 Java,我们有一个项目来制作一个将文本转换为 ASCII 并返回的程序。

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我加密成ASCII的方法是

        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当我运行时,我得到了正确的 output,所以如果我输入

11 11

I would get我会得到

49 49 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2 49 49 线程“main”中的异常 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:2

What could I do to fix this?我能做些什么来解决这个问题?

You want while (length > 0) or while (tracker < length)你想要while (length > 0)while (tracker < length)

Or you can just do for (Character m: message.toCharArray()) and forego the length, tracker, and charAt method或者您可以只执行for (Character m: message.toCharArray())并放弃长度、跟踪器和 charAt 方法

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... output 我得到的是这个...

2 49 1 1 1 49 0 2 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您在最后看到您的 tracker=2 超出了您的消息字符串的范围,这就是您遇到异常的原因,您可以处理异常或改进您的代码......个人经验 - 如果您是初学者,请使用 for 循环它会让你更清楚代码是如何工作的

Change your code in encrypt method from while(length >= 0) to while(length - 1 >= 0) .将加密方法中的代码从while(length >= 0)更改为while(length - 1 >= 0) Also close the scanner object after using it as it would result in memory leak.使用后还要关闭扫描仪 object,因为它会导致 memory 泄漏。

The length() method return the length of the string, (eg) String message = "Hello"; length = message.length(); length() 方法返回字符串的长度,(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. length 将等于 5。但是在 while 循环中使用它时,您必须使用 message.length() - 1 因为在 Java 中,索引从 0 而不是 1 开始。

I refactored your encypt method and main method and also I feel there is no need to use switch statements.我重构了你的 encypt 方法和 main 方法,而且我觉得没有必要使用 switch 语句。 Replace them with if else statements to reduce redundant code.用 if else 语句替换它们以减少冗余代码。

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();
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么会出现java.lang.StringIndexOutOfBoundsException? - Why am I getting java.lang.StringIndexOutOfBoundsException? 我不断收到java.lang.StringIndexOutOfBoundsException - I keep getting a java.lang.StringIndexOutOfBoundsException 为什么我在代码中的线程“main”java.lang.StringIndexOutOfBoundsException 错误中收到异常? - Why am I receiving an Exception in thread "main" java.lang.StringIndexOutOfBoundsException error in my code? 当我运行程序时,出现错误java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0 - When I run my program i get the error java.lang.StringIndexOutOfBoundsException: String index out of range: 0 我收到“ java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-3” - I am getting “ java.lang.StringIndexOutOfBoundsException: String index out of range: -3 ” java.lang.StringIndexOutOfBOundsException错误我做错了什么 - java.lang.StringIndexOutOfBOundsException Error what did i do wrong 我找不到“ java.lang.StringIndexOutOfBoundsException”错误的原因 - I can't find the reason for “java.lang.StringIndexOutOfBoundsException” error 我不断收到此错误:线程“main”中的异常 java.lang.StringIndexOutOfBoundsException: String index out of range: 28 - I keep getting this error : Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 28 获取java.lang.StringIndexOutOfBoundsException - Getting java.lang.StringIndexOutOfBoundsException 为什么会出现java.lang.StringIndexOutOfBoundsException? - Why is there a java.lang.StringIndexOutOfBoundsException?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM