0

I need to read the contents of a file. The file contains the names various foods and information regarding portions:

Name:                         Portions:
APPLE JUICE, CANNED           1 CUP
APPLE PIE                     1 PIE  

How can I read the entire name of a food item without including the portions?

4444
  • 3,541
  • 10
  • 32
  • 43

2 Answers2

2

Iterate over the chars of the strings and check if the ascii code is a number. Where the numbers have the ascii codes 48 to 57. To get the acsii code of a char do the following:

char c = 'A';
int ascii = (int)c;
System.out.println(ascii); //prints 65

So the whole code would look like:

public int getIndexOfNumber(String s){
    for(int i = 0; i < s.length(); i++){
        int ascii = (int)s.charAt(i);
        if(ascii >= 48 && ascii <= 57)
            return i;
    }
    return -1; //not found
}
Alex VII
  • 930
  • 6
  • 25
0

Assuming you already have your streams set up and reading, (and a space is your delimiter), you could do something like this:

while((line = stream.readLine()) != null)
{
    String[] words = line.split(" ");
    for(int index = 0; index < words.length; index++)
    {
        if(isNumeric(words[index]))
        {
            //you found a number. do something here;
        }
    }
}

defining the function here: How to check if a String is numeric in Java

public static boolean isNumeric(String str)
{
  try  
  {  
    double d = Double.parseDouble(str);  
  }  
  catch(NumberFormatException nfe)  
  {  
    return false;  
  }  
  return true;
}
Community
  • 1
  • 1
AverageGuy
  • 97
  • 1
  • 10