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;
}