2016-04-15 127 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]; 

顯然錯誤檢查需要發生。但這應該適合你。