4593DDJS
4593DDJS

Reputation: 55

Issues with using delimiter

So basically, I'm trying to gather variables from keyboard input and split up the variables using a comma. Though it doesn't seem to be working. It is probably something simple I have overlooked but been trying for a while and cannot figure it out.

public static void main(String[] args) {

      Scanner scan = new Scanner(System.in);

      scan.useDelimiter(",");

      String str1 = scan.next();
      String str2 = scan.next();
      double num1 = scan.nextDouble();
      double num2 = scan.nextDouble();

      System.out.println(str1);
      System.out.println(str2);
      System.out.println(num1);
      System.out.println(num2);

Upvotes: 2

Views: 104

Answers (2)

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

You have to give input like following and then this will work.

 k,h,2,3,

You have to put , end of the input as well.

 name,name2,54.7,98.6,

Or change your code as follows

   Scanner scan = new Scanner(System.in);
    scan.useDelimiter(",|\\n");  // this will accept input name,name2,54.7,98.6
    String str1 = scan.next();
    String str2 = scan.next();
    double num1 = scan.nextDouble();
    double num2 = scan.nextDouble();

    System.out.println(str1);
    System.out.println(str2);
    System.out.println(num1);
    System.out.println(num2);

Upvotes: 1

ug_
ug_

Reputation: 11440

I compiled your code an ran it with the following input

hello,world,23,42,

and it works fine. However notice the trailing ",". This is because to finish your final input it needs to be delimited. If this is not intended you can solve it by using a regular expression to use commas or new lines for your delimiter. So if you used this line of code:

scan.useDelimiter("[,|\\n]");

makes the following input work

hello,world,23,32

Upvotes: 2

Related Questions