0

I am getting the desired output but my code hasn't finished running. I have used "/" as the delimiter for the scanner class and My code is

Scanner scan = new Scanner(System.in);        
scan.useDelimiter("/");
while(scan.hasNext())
{
  System.out.println(scan.next());
}

My input that i am giving at the Output window is

Input
abcdef/ghijkl/out/

Output:
abcdef
ghijkl
out

And the program is still running.

anshul6297
  • 25
  • 3
  • Are you sure that how many strings(Each string is delimited by '/') you have to read? – cse Jun 19 '17 at 13:32

3 Answers3

2
import java.util.Scanner; // headers MUST be above the first class

// one class needs to have a main() method
public class HelloWorld
{
 // arguments are passed using the text field below this editor
    public static void main(String[] args)
    {
    Scanner scan = new Scanner("abcdef/ghijkl/out/");        
    scan.useDelimiter("/");
    while(scan.hasNext())
        {
          System.out.println(scan.next());
        }
    }
}

This Works.

Your problem may be that you are opening a Scanner for the keyboard (System.in), but you aren't storing the value of your keyboard input anywhere. You would probably want to set your input to a variable, like I have always done in classes that taught Java:

Scanner scan = new Scanner (System.in);
String input = scan.nextLine(); // input: "abcdef/ghijkl/out/"

String[] stringArray = input.split("/");
for(String i : stringArray)
{
    System.out.println(i);
}
Jack F.
  • 114
  • 1
  • 1
  • 9
1

The problem is with next() method. Following is an extract from Oracle Website which states that This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true

public String next()

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.

Community
  • 1
  • 1
cse
  • 3,622
  • 2
  • 17
  • 36
-2

you have to close scan using scan.close();

here you will use it as

Scanner scan = new Scanner(System.in);        
scan.useDelimiter("/");
while(scan.hasNext())
{
  System.out.println(scan.next());
  scan.close();
}
sndpkpr
  • 349
  • 3
  • 14