Home > Blockchain >  Getting integers out of a string containing words in java
Getting integers out of a string containing words in java

Time:04-14

Right now I have a string input along the lines of "Stern Brenda 90 86 45". I'm trying to find a way to get 90 86 and 45 out of that and assign them as ints to tests 3, 2, and 1 respectively to compute an average of them.

      while ((line = reader.readLine()) != null) {
          test3 = line.indexOf(-2, -1);
          test2 = line.indexOf(-5, -4);
          test1 = line.indexOf(-8, -7);

This is returning a value of -1 for each test (I tried using a regular expression to start from index -2 and go until another integer is found. Trying to get a two digit integer (as opposed to if I was just trying to get something like 5 or 6) is really whats throwing me off. Is using the .indexOf method the best way to go about getting these numbers out of the string? If so how am I using it incorrectly?

edit: I found a solution that was relatively simple.

      while ((line = reader.readLine()) != null) {
          String nums = line.replaceAll("[\\D]", "");
          test1 = Integer.parseInt(nums.substring(0,2));
          test2 = Integer.parseInt(nums.substring(2,4));
          test3 = Integer.parseInt(nums.substring(4,6));

For the input "Stern Brenda 90 86 45", this returns 90 for test1, 86 for test2, and 45 for test3 (all as integers).

CodePudding user response:

CheshireMoe almost has it right, but he's accessing a List like an array, which probably won't work. In his example:

Instead of:

  test3 = Integer.parseInt(tokens[tokens.length-1]);
  test2 = Integer.parseInt(tokens[tokens.length-2]);
  test1 = Integer.parseInt(tokens[tokens.length-3]);

Should be:

  test3 = Integer.parseInt(tokens.get(tokens.size()-1));
  test2 = Integer.parseInt(tokens.get(tokens.size()-2));
  test1 = Integer.parseInt(tokens.get(tokens.size()-3));

An easier solution might be just to split the array using the space:

while ((line = reader.readLine()) != null) {

  String [] tokens = line.split(" ");
  if (tokens.length != 5) {  // catch errors in your data!
     throw new Exception();  // <-- use this if you want to stop on bad data
     // continue;  <-- use this if you just want to skip the record, instead
  }
  test3 = Integer.parseInt(tokens[4]);
  test2 = Integer.parseInt(tokens[3]);
  test1 = Integer.parseInt(tokens[2]);
}

Based on your data, you might also consider putting in some validation like I've shown, to catch things like:

  • a value is missing (student didn't take one of the tests)
  • not all the grades were entered as numbers (i.e. bad characters)
  • first and last name both exist

CodePudding user response:

You could use a regular expression to parse the string. This just computes the average. You can also assign the individual values as you deem appropriate.

String s =  "Stern Brenda 90 86 45";
double sum = 0;
  • \\b - a word boundary
  • \\d - one or more digits
  • () - a capture group
  • matching on the string s
Matcher m = Pattern.compile("\\b(\\d )\\b").matcher(s);
int count = 0;
  • a long as find() returns true, you have a match
  • so convert group(1) to a double, add to sum and increment the count.
while (m.find()) {
    sum = Double.parseDouble(m.group(1));
    count  ;
}

When done, compute the average.

System.out.println(sum   " "   count); // just for demo purposes.
if (count > 0) { //just in case
   double avg = sum/count;
   System.out.println("Avg = "   avg);
}

prints

221.0 3
Avg = 73.66666666666667

Check out the Pattern class for more details.

Formatting the final answer may be desirable. See System.out.printf

CodePudding user response:

StringTokenizer is a very useful way to work with data strings that come files or streams. If your data is separated by a specific character (space in this case), StringTokenizer is a easy way to brake a large string into parts & iterate through the data.

Since you don't seem to care about the other 'words' in the line & have not specified if it will be a constant number (middle name?) my example puts all the tokens in an array to get the last three like in the question. I have also added the parseInt() method to convert from strings to int. Here is how you would tokenize your lines.

while ((line = reader.readLine()) != null) {

  List<String> tokens = new ArrayList<>();
  StringTokenizer tokenizer = new StringTokenizer(line, " ");
  while (tokenizer.hasMoreElements()) {
    tokens.add(tokenizer.nextToken());
  }

  test3 = Integer.parseInt(tokens[tokens.length-1]);
  test2 = Integer.parseInt(tokens[tokens.length-2]);
  test1 = Integer.parseInt(tokens[tokens.length-3]);
}
  •  Tags:  
  • java
  • Related