0

I want to save multiple strings in one. Thing is, I don't know how many strings it may be. I'm creating a program that reads calories from a text file and stores them in corresponding arrays.

Here are parts of the text:

 Description of food                         Fat  Food Energy Carbohydrate Protein     Cholesterol Weight Saturated Fat
                                           (Grams) (calories)   (Grams)   (Grams)     (Milligrams) (Grams)  (Grams)


 APPLES, RAW, PEELED, SLICED   1 CUP          0        65          16         0        0       110      0.1
 APPLES, RAW, UNPEELED,2 PER LB1 APPLE        1       125          32         0        0       212      0.1
 APPLES, RAW, UNPEELED,3 PER LB1 APPLE        0        80          21         0        0       138      0.1
 APRICOT NECTAR, NO ADDED VIT C1 CUP          0       140          36         1        0       251       0

Now for the food name, I have an array foodName. I will read the whole string until I reach an int which is the amount.

Here is what I've done so far:

Scanner input = new Scanner("Calories.txt");
while (input.hasNext()) {
    String[] words = input.next().split(" ");
    int lastI;
    for (int i=0; i < words.length; i++) {
        if (isNumeric(words[i])) {
            lastI = i;
            for(int j=lastI; j>=0; j++){
                //What should I put here?
            }
        }
    }
}

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

for the inner most for loop, I kept track of the last index so I could start from it and go backwards.

Problem 1: If I go backwards in the second line, I will copy both lines.

Problem 2: How to save all the strings of the name in one index of foodName?

All help is appreciated :)

4
  • Look at the StringBuilder class. It may be what you want. Commented Jun 19, 2014 at 21:33
  • Are you able to change the formatting of the file? Often cases when using a flat file, you would want to use a standard format such as a CSV (comma separated values) file. This way you can split on each comma. Then loop through each value in the array until you find a number, and move to the next line. Commented Jun 19, 2014 at 21:35
  • for(int j=lastI; j>=0; j++) This is a really bad idea. Also, your question seems unclear. What do you exactly want as one String? Do you mean a String array or a single String? Is that file example exactly how it will be formatted? Commented Jun 19, 2014 at 21:36
  • I want the many strings of the name of the food in one string. say foodName[0] = "APPLES, RAW, PEELED, SLICED"; Yes. Commented Jun 19, 2014 at 21:44

1 Answer 1

3

What you are looking for in Java is called a StringBuilder. You can use this essentially like a string and keep appending onto it.

File file = new File("output.txt");
Scanner input = new Scanner(file);
StringBuilder sb = new StringBuilder();
while (input.hasNextLine()) {
    String[] words = input.nextLine().split(" ");
    for (int i = 0; i < words.length; i++) {
        if (isNumeric(words[i])) {
            break;
        }
        sb.append(words[i] + " ");
    }
    System.out.println(sb);
    sb = new StringBuilder();
}
input.close();

What this does is read the file line by line, creating an array of strings splitting the line on " ". Then, it iterates over each of the strings in the array and checks if it is a number, if it is, it will break the current loop and move onto the next line.

I had the StringBuilder print after each line, and then reset, you should replace this with whatever functionality that you want.

A couples suggestions also for you:

  1. Use a CSV file. Separate everything with commas instead of spaces, it makes parsing extremely easy.
  2. Use regex to check if the string is a number instead of catching exceptions, it is more elegant.

The output of this comes out a little funny because of how you formatted your file. You are parsing on " ", but you added a bunch of extra " " characters in the file to make the format look nice. This messes up your parsing very badly. BUT, this method will parse for you correctly when you fix the format of your flat file.

Output from this was: (note that each line is a separate string. You can see how the file formatting messed up the output)

Description of food                         Fat  Food Energy Carbohydrate Protein     Cholesterol Weight Saturated Fat 
                                       (Grams) (calories)   (Grams)   (Grams)     (Milligrams) (Grams)  (Grams) 


 APPLES, RAW, PEELED, SLICED   
 APPLES, RAW, UNPEELED,2 PER LB1 APPLE        
 APPLES, RAW, UNPEELED,3 PER LB1 APPLE        
 APRICOT NECTAR, NO ADDED VIT C1 CUP      
Sign up to request clarification or add additional context in comments.

1 Comment

Anytime, I am happy that I could help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.