Eli
Eli

Reputation: 75

How would I go about using an integer delimiter? (Java)

So I am trying to read a file using a scanner. This file contains data where there are two towns, and the distance between them follows them on each line. So like this:

Ebor,Guyra,90

I am trying to get each town individual, allowing for duplicates. This is what I have so far:

   // Create scanner for file for data
   Scanner scanner = new Scanner(new File(file)).useDelimiter("(\\p{javaWhitespace}|\\.|,)+");

   // First, count total number of elements in data set
   int dataCount = 0;

   while(scanner.hasNext())
   {
      System.out.print(scanner.next());
      System.out.println();
      dataCount++;
   }

Right now, the program prints out each piece of information, whether it is a town name, or an integer value. Like so:

Ebor

Guyra

90

How can I make it so I have an output like this for each line:

Ebor

Guyra

Thank you!

Upvotes: 0

Views: 901

Answers (3)

mstill3
mstill3

Reputation: 132

I wrote a method called intParsable:

public static boolean intParsable(String str)
{
    int n = -1;
    try
    {
        n = Integer.parseInt(str);
    }
    catch(Exception e) {}
    return n != -1;
}

Then in your while loop I would have:

String input = scanner.next();
if(!intParsable(input))
{
    System.out.print(input);
    System.out.println();
    dataCount++;
}

Upvotes: 1

KarlR
KarlR

Reputation: 1615

Try it that way:

    Scanner scanner = new Scanner(new File(file));
    int dataCount = 0;

    while(scanner.hasNext())
    {
        String[] line = scanner.nextLine().split(",");
        for(String e : line) {
            if (!e.matches("-?\\d+")) System.out.println(e);;
        }
        System.out.println();
        dataCount++;
    }
}

We will go line by line, split it to array and check with regular expression if it is integer.

-? stays for negative sign, could have none or one
\\d+ stays for one or more digits

Example input:

Ebor,Guyra,90
Warsaw,Paris,1000

Output:

Ebor
Guyra

Warsaw
Paris

Upvotes: 1

Gil Vegliach
Gil Vegliach

Reputation: 3562

Assuming well-formed input, just modify the loop as:

while(scanner.hasNext())
{
    System.out.print(scanner.next());
    System.out.print(scanner.next());
    System.out.println();
    scanner.next();
    dataCount += 3;
}

Otherwise, if the input is not well-formed, check with hasNext() before each next() call if you need to break the loop there.

Upvotes: 3

Related Questions