简体   繁体   English

简单的Java程序无法正常工作-while循环

[英]simple java program not working — while-loop

So I'm fairly new to programming, and I'm working on a simple practice program that finds a letters order in the alphabet. 因此,我对编程还不陌生,我正在研究一个简单的练习程序,该程序可以找到字母中的字母顺序。 This should have been pretty easy...but for some reason I get a StringIndexOutOfBoundsException when I add a while loop. 这应该很容易...但是由于某种原因,当我添加一个while循环时,我得到了StringIndexOutOfBoundsException。 So the program does do what it should the first time...but will not allow me to test again with out re-running the program. 因此,该程序确实执行了第一次应该执行的操作...但是不允许我在不重新运行该程序的情况下再次进行测试。 I tested the while loop with nothing but a simple print statement inside and it worked, so I'm confused as to why the while loop isn't working with my alphabet program. 我测试了while循环,只在其中测试了一个简单的print语句,它就起作用了,所以我对为何while循环不适用于我的字母程序感到困惑。

Any help would be greatly appreciated thanks! 任何帮助将不胜感激,谢谢!

import java.io.*;
public class test {


    public static void main(String[] args) throws IOException 
    {
        BufferedReader in;
        in = new BufferedReader (new InputStreamReader (System.in));
        boolean again=true;
        String response;

        while (again)
        {

            System.out.println("Enter a letter to find it's order in the alphabet");

            char theLetter = (char) in.read();

            System.out.println(theLetter + " is the " + convertLetter(theLetter) + "th letter of the alphabet");

            System.out.println("want to play again?");

            response = in.readLine();

            if (response.charAt(0)=='n')
            {
                again=false;
            }
        }

        System.out.println("end program");
    }


    public static int convertLetter(char TheLetter)
    {
        //number value 'a'=97
        //number value 'b'=98
        //number value 'c'=99

        //subtracting 'a' from any other number will reveal how many places away that number is from the start
        //thus finding it's chronological place in the alphabet

        int NumberValue= (int)TheLetter;
        int a = 'a';

        int CalulateOrder = (NumberValue - a) + 1; 

        return CalulateOrder;

    }
}
 if (response.charAt(0)=='n') 

如果String为空"" ,则位置0处将没有字符。在执行charAt()之前进行检查

When you hit enter for the original char, that newline is still in the buffer since you only call read() and only get 1 character, leaving the newline in the buffer from hitting enter. 当您按回车键输入原始字符时,该换行符仍在缓冲区中,因为您仅调用read()且仅获得1个字符,因此换行符不会按回车键而保留在缓冲区中。 So when you call readLine it simply hits that newline and returns an empty string. 因此,当您调用readLine时,它仅命中该换行符并返回一个空字符串。

You can test this by typing something with more than one character when it first asks you for a character, and it will go for a second loop since the readLine will return a non-empty string. 您可以通过在第一次要求您输入一个字符时输入不止一个字符来测试该字符,并且由于readLine将返回非空字符串,因此它将进行第二次循环。

To fix this change your original read() to readLine() so that it gets the newline caused from you hitting enter, then just grab the first character from the string. 要解决此问题,请将原始的read()更改为readLine(),这样它就可以获取您按回车键所引起的换行符,然后只需从字符串中获取第一个字符即可。

This should fix it: 这应该解决它:

    import java.io.*;

public class test {

    public static void main(String[] args) throws IOException {
        BufferedReader in;
        in = new BufferedReader (new InputStreamReader (System.in));
        boolean again=true;
        String response;

        while (again) {
            System.out.println("Enter a letter to find it's order in the alphabet");
            response = in.readLine();
            if (response.length() > 0) {
                char theLetter = response.charAt(0);

                System.out.println(theLetter + " is the " + convertLetter(theLetter) + "th letter of the alphabet");
                System.out.println("want to play again?");

                response = in.readLine();
                if (response.length() > 0 && response.charAt(0)=='n') {
                    again=false;
                }
            }
        }
        System.out.println("end program");
    }

    public static int convertLetter(char TheLetter) {
        return (TheLetter - 'a') + 1;
    }

}

is the length of response null or "" ? response的长度为null还是"" if it is you will not be able to get the char at index 0 如果是,您将无法获得索引0处的char

The only place you access a string index is at if (response.charAt(0) == 'n') so that is most likely your problem area. 您访问字符串索引的唯一位置是if (response.charAt(0) == 'n')因此很可能是您遇到的问题所在。

if(response.length() > 0 && response.charAt(0) == 'n')

Should do the trick. 应该做到的。

Edit: As @TreySchroeder points out, there is another problem with your program, in that you don't read the full line at first. 编辑:正如@TreySchroeder指出的那样,您的程序还有另一个问题,因为您一开始没有阅读整行。 Put in.readLine(); 放入in.readLine(); after your initial theLetter = (char) in.read(); 在您最初的theLetter = (char) in.read(); , and use this fix for the other issue. ,并将此修补程序用于其他问题。

I bet the culprit is that you're hitting "enter" at the want to play again? 我敢打赌,罪魁祸首是您要want to play again? “进入” want to play again? prompt. 提示。 The in.readLine(); in.readLine(); returns the line without the trailing newline (see the javadocs ), which means that if you only press "enter" it will return an empty string, thus the StringOutOfBoundException while checking the first char. 返回没有尾随换行符的行(请参阅javadocs ),这意味着如果仅按“ enter”,它将返回一个空字符串,因此在检查第一个字符时将返回StringOutOfBoundException。

Check for the empty string before checking for the char: 在检查char之前检查空字符串:

if(response.length() > 0 && response.charAt(0) == 'n')
if (response.isEmpty() && response.charAt(0)=='n')

将避免异常。

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

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