java Scanner.hasNext()用法

时间:2014-02-08 02:16:30

标签: java java.util.scanner

public static void main(String args[]){
    Scanner in = new Scanner(System.in);
    String a = in.next();
    if (in.hasNext()) {
        System.out.println("OK")
    }  else {
        System.out.println("error");
    }
}

我想要的是: 如果用户键入包含多个单词的String,则打印“OK”。 如果用户键入只有一个单词的字符串,则打印“错误”。

然而,它效果不佳。当我输入一个单词作为输入时,它不会打印“错误”,我不知道为什么。

5 个答案:

答案 0 :(得分:1)

读一行,然后检查是否有多个单词。

    String a = in.nextLine();
    if( a.trim().split("\\s").length> 1 ){  
        System.out.println("OK");
    }  else {
        System.out.println("error");
    }

答案 1 :(得分:0)

如果您有任何新的输入,您的情况会解决。尝试contains(" ")之类的内容来测试输入以包含空格。如果您想确保输入不仅包含空格而且还包含其他一些字符,请先使用trim()

答案 2 :(得分:0)

hasNext()是一个阻塞调用。你的程序会坐着,直到有人输入一个字母,然后转到System.out.println(“OK”);线。我建议使用一个InputStreamReader传入System.in到构造函数,然后读取输入并从那里确定它的长度。希望它有所帮助。

答案 3 :(得分:0)

来自Scanner#hasNext() documentation

  

如果此扫描器的输入中有另一个标记,则返回true。此方法可能会在等待扫描输入时阻塞。扫描仪不会超过任何输入。

因此,如果只有一个字,扫描仪将等待下一个输入阻止您的程序。

考虑用nextLine()阅读整行,并检查它是否包含很少的单词 你可以像现在这样做,但这一次是根据你从用户那里得到的数据创建Scanner。

您还可以使用line.trim().indexOf(" ") == -1条件来确定String中间是否包含空格。

答案 4 :(得分:0)

Scanner#hasNext()将返回一个布尔值,表示whether or notmore input

只要用户没有输入end-of-file指标,hasNext()就会返回true

  

文件结束指示符是system-dependent keystroke组合   用户输入以表示没有更多数据要输入。

     在UNIX / Linux / Mac OS X上

ctrl + d ,,,在Windows上它 ctrl + z

看一下这个简单的例子来看看如何使用它

// Fig. 5.9: LetterGrades.java
// LetterGrades class uses the switch statement to count letter grades.
import java.util.Scanner;

public class LetterGrades
{
  public static void main(String[] args)
  {
    int total = 0; // sum of grades                  
    int gradeCounter = 0; // number of grades entered
    int aCount = 0; // count of A grades             
    int bCount = 0; // count of B grades             
    int cCount = 0; // count of C grades             
    int dCount = 0; // count of D grades             
    int fCount = 0; // count of F grades             

    Scanner input = new Scanner(System.in);

    System.out.printf("%s%n%s%n %s%n  %s%n",
                      "Enter the integer grades in the range 0–100.",
                      "Type the end-of-file indicator to terminate input:",
                      "On UNIX/Linux/Mac OS X type <Ctrl> d then press Enter",
                      "On Windows type <Ctrl> z then press Enter");

    // loop until user enters the end-of-file indicator
    while (input.hasNext())
    {
      int grade = input.nextInt(); // read grade
      total += grade; // add grade to total
      ++gradeCounter; // increment number of grades

      //  increment appropriate letter-grade counter
      switch (grade / 10)                           
      {                                             
        case 9: // grade was between 90            
        case 10: // and 100, inclusive             
        ++aCount;                               
        break; // exits switch                  

        case 8: // grade was between 80 and 89     
        ++bCount;                               
        break; // exits switch                  

        case 7: // grade was between 70 and 79     
        ++cCount;                               
        break; // exits switch                  

        case 6: // grade was between 60 and 69     
        ++dCount;                               
        break; // exits switch                  

        default: // grade was less than 60         
        ++fCount;                               
        break; // optional; exits switch anyway 
      } // end switch                               
    } // end while

    // display grade report
    System.out.printf("%nGrade Report:%n");

    // if user entered at least one grade...
    if (gradeCounter != 0)
    {
      // calculate average of all grades entered
      double average = (double) total / gradeCounter;

      // output summary of results
      System.out.printf("Total of the %d grades entered is %d%n",
                        gradeCounter, total);
      System.out.printf("Class average is %.2f%n", average);
      System.out.printf("%n%s%n%s%d%n%s%d%n%s%d%n%s%d%n%s%d%n",
                        "Number of students who received each grade:",
                        "A: ", aCount,   // display number of A grades
                        "B: ", bCount,   // display number of B grades
                        "C: ", cCount,   // display number of C grades
                        "D: ", dCount,   // display number of D grades
                        "F: ", fCount); // display number of F grades
    } // end if
    else // no grades were entered, so output appropriate message
      System.out.println("No grades were entered");
  } // end main
} // end class LetterGrades

,输出将是这样的

Enter the integer grades in the range 0–100.
Type the end-of-file indicator to terminate input:
   On UNIX/Linux/Mac OS X type <Ctrl> d then press Enter
   On Windows type <Ctrl> z then press Enter
99
92
45
57
63
71
76
85
90
100
^Z

Grade Report:
Total of the 10 grades entered is 778
Class average is 77.80

Number of students who received each grade:
A: 4
B: 1
C: 2
D: 1
F: 2

资源Learning Path: Professional Java DeveloperJava™ How To Program (Early Objects), Tenth Edition