0

I have the following text file (answers.txt):

Problem A: 23|47|32|20

Problem B: 40|50|30|45

Problem C: 5|8|11|14

Problem D: 20|23|25|30

What I need is something that will read the problem that I tell it(Problem A, Problem B), then read the numbers after it, which are separated by the lines, and print it out like this:

Answers for Problem A: a.23 b.47 c.32 d.20

Does anyone know how this can be done? I've been stuck on it for a while.

Community
  • 1
  • 1
user2221854
  • 1
  • 1
  • 1

8 Answers8

1

Read the lines one by one, split the lines at " " first. The you will get an array with three parts "Problem", "A:" and "23|47|32|20". Then split the third part at "|" so you will get a second array with four parts "23,"47","32","20".

Combine all to get the output you want.

If you want info on how to read lines from a file, or spilt strings then there are billions of tutorials online on how to do that so I wont go into detail on how its done. IM sure you can find them.

Jakob
  • 751
  • 4
  • 17
0

Check out this code! It assumes that you have such file format:

Problem A:
23|7|32|20
Problem B:
40|50|30|45
Problem C:
5|8|11|14
Problem D:
20|23|25|30

because you wrote "numbers after it, which are separated by the lines"

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;

public class Demo {

public static void main(String[] args) throws FileNotFoundException {
    Scanner sc = new Scanner(new File("answers.txt"));
    List<String> dataList = new ArrayList<String>();
    while(sc.hasNextLine()){
        dataList.add(sc.nextLine());
    }
    System.out.println(dataList);       
    Map<String,String> map = new HashMap<String,String>();
    for(int i=0;i<dataList.size();i=i+2){
        map.put(dataList.get(i),dataList.get(i+1));
    }

    for(Entry<String,String> en:map.entrySet()){
        System.out.println(en.getKey()+" : "+en.getValue());
    }
    String problemC = map.get("Problem C:");
    String splitted[] = problemC.split("\\|");
    System.out.println("Get me problem C: "+String.format("a:%s, b:%s, c:%s, d:%s",splitted[0],splitted[1],splitted[2],splitted[3]));
}

}

Didar Burmaganov
  • 640
  • 1
  • 8
  • 22
0

Hope this helps!

    public static void main(String args[])
{
    BufferedReader br = new BufferedReader(new FileReader(new File("answers.txt")));
    String lineRead  = null;
    String problem = "Problem A";//Get this from user Input
    List<String> numberData = new ArrayList<String>();
    while((lineRead = br.readLine())!=null)
    {
        if(lineRead.contains(problem))
        {
            StringTokenizer st = new StringTokenizer(lineRead,":");
            String problemPart = st.nextToken();
            String numbersPart = st.nextToken();
            st = new StringTokenizer(lineRead,"|");
            while(st.hasMoreTokens())
            {
                String number = st.nextToken();
                System.out.println("Number is: " + number);
                numberData.add(number);
            }
            break;
        }
    }
    System.out.println("Answers for " + problem + " : " + numberData );
}
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
0

Read the lines one by one, split the lines with :. The you will get an array with two parts "Problem A:" and "23|47|32|20". Then split the second part at "|" so you will get a second array with four parts "23,"47","32","20".

Combining all this you will get the output you want.

Cheers!

Bhavesh Shah
  • 3,299
  • 11
  • 49
  • 73
0

Use java.util.Scanner and you can filter the integers in the file.

Scanner s = new Scanner (new File ("answers.txt")).useDelimiter("\\s+");
while (s.hasNext()) {
    if (s.hasNextInt()) { // check if next token is integer
        System.out.print(s.nextInt());
    } else {
        s.next(); // else read the next token
    }
}
Lucky
  • 16,787
  • 19
  • 117
  • 151
0

Do you know how to read line by line ? If not , chect it How to read a large text file line by line in java?

To sub your string data there have many ways to do. You can sub as you wish. Here for my code..

    String data = yourReader.readLine();
    String problem = data.substring("Problem".length(), data.indexOf(":"));
    System.err.println("Problem is " + problem);
    data = data.substring(data.indexOf(":") + 2, data.length());
    String[] temp = data.split("\\|");
    for (String result : temp) {
        System.out.println(result);
    }
Community
  • 1
  • 1
Cataclysm
  • 7,592
  • 21
  • 74
  • 123
0

Assuming there are always four possible answers as in your Example:

// read complete file in fileAsString
String regex = "^(Problem \\w+): (\\d+)\\|(\\d+)\\|(\\d+)\\|(\\d+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(fileAsString);
//and so on, read all the Problems using matcher.find() and matcher.group(int) to get the parts
// put in a Map  maybe?
// output the one you want...
kutschkem
  • 7,826
  • 3
  • 21
  • 56
0

I might suggest creating a simple data type for the purpose of organization:

public class ProblemAnswer {
  private final String problem;
  private final String[] answers;

  public ProblemAnswer(String problem, String[] answers) {
    this.problem = problem;
    this.answers = new String[answers.length];
    for (int i = 0; i < answers.length; i++) {
      this.answers[i] = answers[i];
    }
  }

  public String getProblem() {
    return this.problem;
  }

  public String[] getAnswers() {
    return this.answers;
  }

  public String getA() {
    return this.answers[0];
  }

  public String getB() {
    return this.answers[1];
  }

  public String getC() {
    return this.answers[2];
  }

  public String getD() {
    return this.answers[3];
  }
}

Then the reading from the text file would look something like this:

public void read() {
  Scanner s = new Scanner("answers.txt");
  ArrayList<String> lines = new ArrayList<String>();
  while (s.hasNext()) {
    lines.add(s.nextLine());//first separate by line  
  }
  ProblemAnswer[] answerKey = new ProblemAnswer[lines.size()];
  for (int i = 0; i < lines.size(); i++) {
    String[] divide = lines.get(i).split(": "); //0 is the problem name, 1 is the list                 
                                                //of answers
    String[] answers = divide[1].split("|");  //an array of the answers to a given
                                              //question
    answerKey[i] = new ProblemAnswer(divide[0], answers); //add a new ProblemAnswer 
                                                          //object to the key
  }
}

Now that leaves you with an answer key with ProblemAnswer objects which is easily checked with a simple .equals() comparison on the getProblem() method, and whatever index is matched, you have all the answers neatly arranged right within that same object.

Sam Hazleton
  • 470
  • 1
  • 5
  • 21