简体   繁体   English

JAVA:扫描器无法读取下一行// //返回空字符串

[英]JAVA: Scanner doesn't read next line // returns empty string

So I am programming Snake at the moment and i have a Method to read an an integer value from the console. 因此,我目前正在对Snake进行编程,我有一个方法可以从控制台读取一个整数值。
When my Method throws a mistake - or atleast when i return to that method - it doesn't read in a new line from input but just passes aa empty string. 当我的方法抛出错误时(或者至少返回到该方法时),它不会从输入中读取新行,而只是传递一个空字符串。
Here is my code: 这是我的代码:

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

I've declared "sc" as a static class variable static Scanner sc = new Scanner(System.in); 我已经将“ sc”声明为静态类变量static Scanner sc = new Scanner(System.in); at the beginnning of my programm. 在我的程序开始时。

Why does the scanner return an empty String? 扫描器为什么返回空字符串? - without asking for user input - -无需用户输入-
And yes i am aware of the Method .readNextInt, but i find it easyer to handle exceptions like this. 是的,我知道方法.readNextInt,但是我发现更容易处理此类异常。

Thanks @Seelenvirtuose who brought me to the right track of the solution! 感谢@Seelenvirtuose,他使我正确地找到了解决方案!

I said, if in another place sc.nextInt() was used, you have a pending newline that was not consumed. 我说过,如果在其他地方使用sc.nextInt(),则您有一个未使用的待处理换行符。 The next sc.nextLine() only consumes this newline and does not give the priority to enter anything. 下一个sc.nextLine()仅使用此换行符,而不优先输入任何内容。 The problem, therefore, is in another portion of your code! 因此,问题出在代码的另一部分!

The solution was that in some parts of my code i was using sc.next() which only reads in the next string untill the whitespace (if i am not mistaken) and not sc.nextLine() . 解决的办法是在我的代码的某些部分中,我使用的是sc.next() ,它仅读取下一个字符串,直到空白(如果我没有记错),而不是sc.nextLine()
So I've changed all sc.next() to sc.nextLine() not it works just fine. 所以,我已经改变了所有sc.next()sc.nextLine()不只是正常工作。

There are 2 other solutions that I've found while doing trail and error: 在进行跟踪和错误处理时,我发现了另外两种解决方案:
a) Write sc.reset() which does " Resetting a scanner discards all of its explicit state information[...] " bevor accesing the sc.nextLine() command or a)编写sc.reset() ,以便通过使用sc.nextLine()命令来“ 重置扫描器会丢弃其所有显式状态信息[...] ”,或
b) Just create a new instance of the Scanner class. b)只需创建一个Scanner类的新实例。

Thanks again to Seelenvirtuose . 再次感谢Seelenvirtuose

I solved using two different scanner: one for reading of int and float values and another for reading String. 我使用两种不同的扫描仪解决了:一种用于读取int和float值,另一种用于读取String。

Scanner scanString = new Scanner(System.in);
Scanner scanIntFloat = new Scanner(System.in);

int cod = scanIntFloat.nextInt();
String name = scanString.nextLine();

Elias. 埃里亚斯。

You can use two different Scanners ....... 您可以使用两个不同的扫描仪 .......

First Scanner for reading int , float and double . 第一台用于读取intfloatdouble的扫描程序。

Second Scanner for reading String values. 第二个扫描器,用于读取字符串值。

Like Below...... 像下面...

Scanner scanIntFloat = new Scanner(System.in);
Scanner scanString = new Scanner(System.in);

int cod = scanIntFloat.nextInt();
String name = scanString.nextLine();

Had a similar issue. 发生了类似的问题。 What i did was add a nextLine(); 我所做的是添加了nextLine(); command after the next(); next()之后的命令; command to catch the character filling up the buffer that is inserted where you put your input request. 命令来捕获填充输入请求所在位置插入的缓冲区的字符。

Basically: 基本上:

  • word = scan.next(); 字= scan.next(); --Input whatever word you need -输入您需要的任何单词
  • catcher = scan.nextLine(); catcher = scan.nextLine(); --Catches the character that fills up the buffer -捕获填充缓冲区的字符
  • input2 = scan.nextLine(); input2 = scan.nextLine(); --Input your following line -输入您的下一行

Hope this helps :) 希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM