0
我试图从用户那里抓取3个字符串。如何停止扫描仪?
我现在遇到的问题是,扫描仪永远不会结束/从不存储第一个用户输入值?由于迄今为止我所做的研究数量有限,看起来扫描器方法存在一些复杂性,远远超出了封面。
我现在的代码如下,后面是完整的方法。任何形式的解释将不胜感激。谢谢!
//prompt user for array values by row
System.out.println("Enter matrix values by row: ");
userInput[0] = in.nextLine();
userInput[1] = in.nextLine();
userInput[2] = in.nextLine();
Complete方法:
public static double[][] setArray()
{
//initiate variables
String stringValue = "";
double doubleValue = 0;
//instantiate string array for user input values
String[] userInput = new String[3];
//instantiate return array
double[][] array = new double[3][4];
//prompt user for array values by row
System.out.println("Enter matrix values by row: ");
userInput[0] = in.nextLine();
userInput[1] = in.nextLine();
userInput[2] = in.nextLine();
//stop each scanner
int valueCounter = 0;
for(int eachString = 0; eachString < 3; eachString++)
{
for(int index = 0; index < userInput[eachString].length(); index++)
{
//exception handling
//if string does not contain a space, period, or valid digit
while(userInput[eachString].charAt(index) != ' '
&& userInput[eachString].charAt(index) < '0'
&& userInput[eachString].charAt(index) > '9'
&& userInput[eachString].charAt(index) != '.')
{
System.out.println("Invalid input. Digits must be in integer"
+ " or double form. (i.e. 4 5.0 2.3 9)");
System.out.println("Re-enter given matrix value");
userInput[eachString] = in.nextLine();
}
}
//given string is valid at this point//
//for each index in string value
for(int eachIndex = 0; eachIndex < userInput[eachString].length(); eachIndex++)
{
//while value != ' '... += string... if value == ' ' stop loop
while(userInput[eachString].charAt(eachIndex) != ' ')
{
stringValue += userInput[eachString].charAt(eachIndex);
}
doubleValue = Double.valueOf(stringValue);
array[eachString][valueCounter] = doubleValue;
valueCounter++;//array[0-2][0-3 (valueCounter)]
stringValue = "";//clear string
}
}
return array;
}