2016-04-15 274 views
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; 
} 

回答

0

你会只想打破了扫描仪在一次读取1号,然后询问第二个数字和有关问题

代码然后读入,然后询问第三个数字。

或者你可以让他们提供3个数字除以空格或其他内容,并以字符串的形式读取它,并将每个空格的字符串拆分并解析为每个userInput。

我就这么后者,它会是这个样子:

System.out.println("Enter matrix values by row: "); 
    String temp = in.nextLine(); 
    String[] tempArray = temp.split("\\s+"); 
    userInput[0] = tempArray[0]; 
    userInput[1] = tempArray[1]; 
    userInput[2] = tempArray[2]; 

显然错误检查需要发生。但这应该适合你。