0
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.

user2901156
  • 69
  • 1
  • 5

5 Answers5

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");
    }
Peng Zhang
  • 3,475
  • 4
  • 33
  • 41
  • 1
    If line will be `" word"` after split you will get array which will contain `{"","word"}` so despite only one word from user you will get two elements in array. To make this work you first need to `trim` users data. – Pshemo Feb 08 '14 at 02:38
0

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.

markusthoemmes
  • 3,080
  • 14
  • 23
0

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.

Joshua Hyatt
  • 1,300
  • 2
  • 11
  • 22
0

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.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • What is the case when nextLine() == false? It always waits me to type something, but if I type something, it will be true. It's confusing.. – user2901156 Feb 08 '14 at 03:03
  • @user2901156 `nextLine()` returns String so you can't compare its result with `boolean`. Can you describe your problem more? – Pshemo Feb 08 '14 at 03:08
  • Sorry, it's a typo, it should be hasNext() rather than nextLine()...I'm just wondering why hasNext() asks me to input something because if I input something, it will always have Next.. – user2901156 Feb 08 '14 at 03:16
  • @user2901156 If you would use Scanner on non-dynamic source of data like `String` `new Scanner("some text")` then Scanner would know that after `text` there will be no more text so in this case it `hasNext` would just return `false`. But you are using Scanner on stream, which is dynamic source so scanner can't determine if user send all his data, or just one line, word. In this case since user can be in the middle of writing `hasNext` needs to wait for potential new data. – Pshemo Feb 08 '14 at 03:30
0

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

Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92