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();
コンプリート方法:
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;
}