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

Answer

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

Leave a Reply

Your email address will not be published. Required fields are marked *