如何在java中使用hasNext()函数

问题描述 投票:-3回答:3

我是Java的菜鸟,采取基本步骤。我在CoreJava教科书和这个在线网站上找到了文件:https://www.tutorialspoint.com/java/util/scanner_hasnext.htm作者提到了令牌,我无法理解。此外,我仍然觉得模糊这个功能的主要影响是模糊的。以下是该网站的代码:

package com.tutorialspoint;    
import java.util.*;
import java.util.regex.Pattern;

public class ScannerDemo {
   public static void main(String[] args) {

      String s = "Hello World! 3 + 3.0 = 6";

      // create a new scanner with the specified String Object
      Scanner scanner = new Scanner(s);

      // check if the scanner has a token
      System.out.println("" + scanner.hasNext());

      // print the rest of the string
      System.out.println("" + scanner.nextLine());

      // check if the scanner has a token after printing the line
      System.out.println("" + scanner.hasNext());

      // close the scanner
      scanner.close();
   }
}

我不明白为什么它与第一行不同

System.out.println("" + scanner.hasNext());

和第二个,但结果是不同的(真假)。 ??

java function token
3个回答
0
投票

Scanner将处理输入。在这种情况下,检查hasNext是否有输入字符串中的内容要读取。因为你没有处理任何东西它回答是真的。使用nextLine()消耗输入后,没有任何内容可供您的Scanner使用者处理。然后,hasNext()回答错误。


0
投票

hasNext()函数告诉:你有一个令牌(在你的情况下,你有一个字符串)。

当您第一次调用hasNext()时,它返回true(因为您在scanner对象中链接了字符串)。

当您使用nextLine时,您在输出中表示您的字符串s,因此扫描程序对象不再有其他标记(字符串),因此在第二次调用时,hasNext()返回false。


0
投票

令牌只是使用分隔符模式拆分的扫描仪输入(默认是我相信的空格)。

你第一次得到true作为输出,因为有一个输入(即hasNext()正在做它在锡上说的,它有输入)

然后用nextLine()打印该行

当你再次尝试调用hasNext()时,它是假的,因为基本上你已经在print语句中使用了一行文本(在你的情况下只有一行),所以没有更多的输入,因此hasNext()是假的。

来自文档:

hasNext()

如果此扫描器的输入中有另一个标记,则返回true。

hasNextLine()

如果此扫描器的输入中有另一行,则返回true。

© www.soinside.com 2019 - 2024. All rights reserved.