gpt4 book ai didi

java - 如何使用 charAt() 迭代字符串以验证值是否在范围内?

转载 作者:行者123 更新时间:2023-12-01 14:18:56 25 4
gpt4 key购买 nike

我正在尝试迭代包含用户输入值的字符串。我想验证用户只输入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++;
}

如果有请告诉我

最佳答案

您的评论是正确的;你需要在那里进行第二次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;
}
}
}

关于java - 如何使用 charAt() 迭代字符串以验证值是否在范围内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17818634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com