Search code examples
javastringloopsinputspace

How to just take a space character to register a String from input string in Java?


I have a problem that I couldn't find a solution in any where about the logic of taking string from input. If you help me for that question, I'll be glad. Firstly , my question is that I have to take just a space character to register into a string from input in Java due to I want hasNext() method to return false for my program. As some source says "For the hasNext() method to return false value , next character has to be "whitespace" so only a space character must be enough for the hasNext() method to return false and get out from the loop.

The example code is as follows ;

Scanner scan = new Scanner(System.in);
    int counter=0;
    while (scan.hasNext()) { /*When I just type a space
        character to the console and then
        scan.hasNext() doesn't return false.
        so the program never get out from the loop*/
        counter++;
        System.out.println(counter);
        String s = scan.next();
    }
    scan.close();
    System.out.println("It's outed!");

After typing the console a space character or without a character and pushing the enter button , the string of s has to be like that to get out of the loop as the sources says;

String s = " ";

When I try to just put a space character like above into a string from input and then pushing the enter button. My console doesn't do any process and the counter above doesn't increased. It doesn't take that character above that I write after pushing the enter button.The console only passes to a new line. I researched this situation but I couldn't see any information about that.

1 - How can I just take a space character or without any character from input to register it into a string in Java without a problem like described above ?

2 - There might be another way for the loop above to get out. If there is another solution. I'm looking forward to hear it from you.

Thank you for your helping and understanding. Have a nice day!


Solution

  • I dont know if you want something like this, try it and write a comment

    Scanner sc = new Scanner(System.in);
    int counter = 0;
    String str = "";
    while (! (str = sc.nextLine()).equals(" ")) {
    
      // ==== options ===== //
    
     // if you want when user not typing anything [ Empty ]
      if (str.isEmpty()) {
        break;
      }
    
      // or if user entred "exit"
      if (str.equals("exit")) {
        System.out.println("Exit");
        break;
      }
    
     // ================== //
      counter++;
      System.out.println(counter + " - " + str);
    }
    
    // str = " "; ended the while loop
    System.out.println("--- out ---");