0

我正在尝试迭代一个包含用户输入值的字符串。我想验证用户只输入了 4 个字符,并且它们都在 1 到 4 之间。例如,提示用户使用逗号输入 4 个值,因此他们只能输入 1、2、3、4。如果他们输入其他任何内容,则会再次询问他们。我已经包含了我试图执行验证的代码部分。我也遇到了无法访问的代码错误,这对我来说没有意义。这发生在我关闭 while (true) 循环之后。

        //Entering by ROWS
    //This is for a 4x4 board size using rows
        if (dataSelection == 1) {
        if (boardSize == 1) {
            int row = 1;
            while (row < 5) 
            {
                String row1Values4x4 = "-1";
                while (true) 
                {
                    Scanner firstRow4x4 = new Scanner(System.in);
                    System.out.println("Please enter four values using commas for row " + row); //this needs to loop
                    row1Values4x4 = firstRow4x4.next();
                    row1Values4x4 = row1Values4x4.replaceAll(" ",""); //this is in case user enters numbers with spaces
                    for (int i = 0; i < row1Values4x4.length(); i++) {
                        char c = row1Values4x4.charAt(i);
                        if (row1Values4x4.length() == 7 && c == 48) //I entered 48 in order to test if it is using ascii value (48 = 0) {
                            break;
                        }
                    }
                } //I think I need to include another break in order to escape the second loop? 
                String strArray[] = row1Values4x4.split(","); //This is where I get an unreachable code error 
                int arraySidesInteger[] = new int[strArray.length];
                for (int i = 0;  i < strArray.length;  i++) {
                    arraySidesInteger[i] = Integer.parseInt(strArray[i]);
                }
                fourArray[row-1] = arraySidesInteger;
                for (int i = 0; i < fourArray.length; i++) {
                    for (int j = 0; j < fourArray.length; j++)
                        System.out.print(fourArray[i][j] + " ");
                    System.out.println();
                }
                row++;
                }

请让我知道是否有

4

2 回答 2

1

你的评论是对的;你需要一秒钟break。存在的break那个只跳出for循环,而不是while循环。

也许代替

while (true) 
{
    // do some stuff
    for (/* some other stuff */) 
    {
        // even more stuff
        if (/* should we break */) 
        {
            break;
        }
    }
}

你可以尝试类似的东西

boolean done = false;
while (!done) 
{
    // do some stuff
    for (/* some other stuff */) 
    {
        // even more stuff
        if (/* should we break */) 
        {
            done = true;
            break;
        }
    }
}
于 2013-07-23T19:04:09.257 回答
0

为什么不在字符串中使用 split 方法

String s = userInput;
String[] inputArray = s.split(",");
for(int i = 0; i < inputArray.length; i++){
    // check if the character is correct here
}
于 2013-07-23T19:21:00.160 回答