【发布时间】:2013-07-23 18:51:02
【问题描述】:
我正在尝试迭代一个包含用户输入值的字符串。我想验证用户只输入了 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++;
}
如果有请告诉我
【问题讨论】:
-
你为什么使用矩阵?
-
//I entered 48 in order to test if it is using ascii value (48 = 0)fwiw,你可以用c == '0'代替c == 48。 -
@ColeJohnson 我正在使用矩阵或二维数组来按行和列对用户输入进行排序。它适用于 4x4 数独游戏。
-
@DennisMeng 我也试过了。出于某种原因,我的 for 循环或其他东西没有遍历输入的值或其他东西。它不承认我暂时尝试将输入限制为仅 0 值以进行测试。
-
嗯,那是因为这不是你要求它做的事情。如果字符串长度为 7 个字符并且您正在阅读的当前字符是
0,则您要求它中断。你到底想在那个循环中做什么?
标签: java string validation