2016-01-20 89 views
0

所以我现在编程Snake,我有一个方法来从控制台读取一个整数值。
当我的方法抛出一个错误 - 或至少当我回到那个方法时 - 它不会从输入中读入新行,而只是传递一个空字符串。
这里是我的代码:JAVA:扫描仪不读取下一行//返回空字符串

static int readInInt() 
{ 
    //We Read in the next line the user enters 
    String s = sc.nextLine(); 
    //x returns -1 if mistake happens 
    int x = -1; 

    try 
    { 
     //Now we try to parse that int 
     x = Integer.parseInt(s); 
     x = Math.abs(x); 
     System.out.println("Setting the speed to " + (x*100) + "ms."); 
    } 
    catch(NumberFormatException ex) 
    { 
     //If we can't parse it we try to get the ints with a regex and then parse it 
     System.out.println("Du hast eine nummer eingetippt die das System nicht analysieren kann."); 
     System.out.println("Das System probiert jetzt die Nummer die du eingetippt hast über umwege zu Analysieren."); 
     s = s.replaceAll("[^-?0-9]+", ""); 
     try 
     { 
      x = Integer.parseInt(s); 
     } 
     catch(Exception e) 
     { 
      //and if that doesnt work we just say Error! 
      System.out.println("Error Handling didn't work.\n" 
        + "Please try again with just a simple number (e.g. 7)");    
      //Return an Error in form of -1 
      return -1; 
     } 
     x = Math.abs(x); 
     System.out.println("Setting the speed to " + (x*100) + "ms."); 
    } 

    return x; 
} 

我已经声明“SC”作为一个静态类在我PROGRAMM的beginnning变量static Scanner sc = new Scanner(System.in);

扫描仪为什么会返回空字符串? - 不要求用户输入 -
是的,我知道Method.readNextInt,但我发现它easyer处理这样的异常。

+0

你显示的代码片段似乎没问题。我假设你的代码的另一部分有一个“问题”。很有可能,你已经用'sc.nextInt()'或类似的方式读过其他一些输入。此方法_不消耗控制台上键入的换行符。如果你进入你的显示方法,那么'String s = sc.nextLine()'语句直接使用这个挂起的换行符,而不用等待任何其他输入。你也得看看你的其他代码。 – Seelenvirtuose

+0

@Seelenvirtuose 感谢您的回答。 Bevor我再次访问该方法,我问用户他是否想要一个新游戏。 (y/n答案)。 如果他想要一个新的游戏,returnInt()方法会再次被使用。 但是,这不应该是问题eversicne我访问sc.nextLine()通过我的程序(改变方向等),所以我不明白为什么它在那种特定情况下这样做 –

+1

我说,如果在_another_ place sc .nextInt()'被使用,你有一个未被使用的挂起的换行符。下一个'sc.nextLine()'只消耗这个换行符,并且不会优先输入任何内容。因此,问题出现在代码的另一部分! – Seelenvirtuose

回答

0

谢谢@Seelenvirtuose谁带我到解决方案的正确轨道!

I said, if in another place sc.nextInt() was used, you have a pending newline that was not consumed. The next sc.nextLine() only consumes this newline and does not give the priority to enter anything. The problem, therefore, is in another portion of your code! –

的解决方案是,在我的代码一些部分我使用sc.next()其中只有下一个字符串直到空格中读取(如果我没有记错的话),而不是sc.nextLine()
所以我已经把所有sc.next()更改为sc.nextLine()不是它工作得很好。

有同时做试错,我已经找到了2个其他解决方案:
一)Wrtie sc.reset()它确实“重置扫描器会丢弃其所有明确的状态信息。[...]” bevor accesing的sc.nextLine()命令或
b)只需创建一个新的实例扫描仪类。

再次感谢Seelenvirtuose