java Scanner.hasNext() usage

2019-08-24 19:08发布

问题:

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

What I want is: if the user type in a String with more than one word, print "OK". if the user type in a String with only one word, print "error".

However, it doesn't work well. When I type a single word as an input, it doesn't print "error" and I don't know why.

回答1:

Read a line and then check whether there are more than one word.

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


回答2:

Your condition resolves true, if you have any kind of new input. Try something like contains(" ") for testing your input to contain spaces. If you want to make sure the input doesn't just contain spaces but also some other characters, use trim() before.



回答3:

hasNext() is a blocking call. Your program is going to sit around until someone types a letter, and then go to the System.out.println("OK"); line. I would recommend using an InputStreamReader passing in System.in to the constructor, and then reading the input and determining its length from there. Hope it helps.



回答4:

From Scanner#hasNext() documentation

Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.

So in case of only one word scanner will wait for next input blocking your program.

Consider reading entire line with nextLine() and checking if it contains few words.
You can do it same way you are doing now, but this time create Scanner based on data from line you got from user.

You can also use line.trim().indexOf(" ") == -1 condition to determine if String doesn't contain whitespace in the middle of words.



回答5:

Scanner#hasNext() is going to return a boolean value indicating whether or not there is more input

and as long as the user has not entered end-of-file indicator, hasNext() is going to return true

The end-of-file indicator is a system-dependent keystroke combination which the user enters to indicate that there’s no more data to input.

on UNIX/Linux/Mac OS X it's ctrl + d,,, On Windows it's ctrl + z

look at this simple example to see how to use it

// 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

and the output will be something like this

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

Resources Learning Path: Professional Java Developer and Java™ How To Program (Early Objects), Tenth Edition