Sorting Output of a HashMap Program Alphabetically [duplicate] - java

This question already has answers here:
Sorting a text file in Java
(4 answers)
How can I sort Map values by key in Java?
(17 answers)
Closed 6 years ago.
This is the code I have that reads two files, one with words and the other with the scrambled letters. The program reads and matches the scrambled letters to words in the file. It works but I want to the output to be in alphabetical order. Where in my code can I put in a sort?
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[]) throws Exception
{
BufferedReader dictionary = new BufferedReader( new FileReader(args[0]) );
BufferedReader jumbles = new BufferedReader( new FileReader(args[1]) );
HashMap<String, List<String>> lookup = new HashMap<String, List<String>>();
while(dictionary.ready())
{
String word = dictionary.readLine();
addWord(word, lookup);
}
dictionary.close();
while(jumbles.ready())
{
String jWord = jumbles.readLine();
List<String>dWords= lookup.get(createKey(jWord));
String wordsString = Arrays.toString(dWords.toArray()).replace("[", "").replace("]", "").replace(",", "").trim();
if(dWords != null){
System.out.println(jWord + " " + wordsString);
}
}
jumbles.close();
}
private static String createKey(String word)
{
char[] cword = word.toCharArray();
Arrays.sort(cword);
return new String(cword);
}
private static void addWord(String word, Map<String, List<String>> lookup)
{
String key = createKey(word);
List<String> list = lookup.get(key);
if(list == null)
{
list = new ArrayList<String>();
lookup.put(key, list);
}
list.add(word);
}
}
outputs:
atc act cat tac
otsp post pots stop spot tops opts
gdo dog god
atr rat tar art
arpt trap tarp part
grof frog
sylogs glossy
What I want:
arpt part tarp trap
atc act cat tac
atr art rat tar
gdo dog god
grof frog
otsp opts post pots spot stop tops
sylogs glossy
nevermind.
Fixed it with:
while(jumbles.ready())
{
jSorted.add(jumbles.readLine());
}
jumbles.close();
Collections.sort(jSorted);
for(int i = 0; i < jSorted.size(); i++)
{
String jWord = jSorted.get(i);
List<String>dWords= lookup.get(createKey(jWord));
String wordsString = Arrays.toString(dWords.toArray()).replace("[", "").replace("]", "").replace(",", "").trim();
if(dWords != null){
System.out.println(jWord + " " + wordsString);
}
}

You can create a list of strings and then sort them
List<String> result = new ArrayList<>();
while(jumbles.ready())
{
String jWord = jumbles.readLine();
List<String>dWords= lookup.get(createKey(jWord));
String wordsString = Arrays.toString(dWords.toArray()).replace("[", "").replace("]", "").replace(",", "").trim();
if(dWords != null){
result.add(jWord + " " + wordsString);
}
}
jumbles.close();
result.sort(String::compareTo);
result.forEach(System.out::println);

Related

Why aren't my Words connecting in Undirected/Unweighted Graph when using BFS?

Issue in my code, not sure why NO connections are found in the Graph built with the words.
ArrayList<String> words = new ArrayList<String>();
words.add("hello");
words.add("there");
words.add("here");
words.add("about");
Graph g = new Graph(words.size());
for(String word: words) {
for(String word2: words){
g.addEdge(words.indexOf(word), words.indexOf(word2));
}
}
BufferedReader readValues =
new BufferedReader(new InputStreamReader(new FileInputStream("values.txt")));
while(true)
{
String line = readTestFile.readLine();
if (line == null) { break; }
assert line.length() == 11;
String start = line.substring(0, 5);
String goal = line.substring(6, 11);
BreadthFirstPaths bfs = new BreadthFirstPaths(g, words.indexOf(start));
if (bfs.hasPathTo(words.indexOf(goal))) {
System.out.println(bfs.distTo(words.indexOf(goal)));
for (int v : bfs.pathTo(words.indexOf(goal))) {
System.out.println(v);
}
}
else System.out.println("Nothing");
}
Contents of the Text file:
hello there
hello here
about here
I seem to get:
Nothing
Nothing
Nothing
Nothing
Nothing
Not sure of why?
EDIT: OP seems to have trouble with the code here, especially, the graph. I do not know specifically why, but, I am sure there are those who do.
I suppose you are using the source code from the excellent book from Robert Sedgewick and Kevin Wayne about algorithms implementation in Java Algorithms, 4th Edition.
There is no reason why your code should not work fine. Please, consider the following test based on your code:
public static void main(String... args) throws IOException {
ArrayList<String> words = new ArrayList<String>();
words.add("hello");
words.add("there");
words.add("here");
words.add("about");
Graph g = new Graph(words.size());
for(String word: words) {
for(String word2: words){
g.addEdge(words.indexOf(word), words.indexOf(word2));
}
}
BufferedReader readValues = null;
try {
readValues =
new BufferedReader(new InputStreamReader(new FileInputStream("values.txt")));
String line = null;
while ((line = readValues.readLine()) != null) {
// assert line.length() == 11;
String[] tokens = line.split(" ");
String start = tokens[0];
String goal = tokens[1];
BreadthFirstPaths bfs = new BreadthFirstPaths(g, words.indexOf(start));
if (bfs.hasPathTo(words.indexOf(goal))) {
System.out.println("Shortest path distance from " + start + " to " + goal + " = " + bfs.distTo(words.indexOf(goal)));
StringBuilder path = new StringBuilder();
String sep = "";
for (int v : bfs.pathTo(words.indexOf(goal))) {
path.append(sep).append(v);
sep = " -> ";
}
System.out.println("Shortest path = " + path.toString());
} else System.out.println("Nothing");
}
} finally {
if (readValues != null) {
try {
readValues.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
If you run this program with the text file that you indicated it will produce an output similar to the following:
Shortest path distance from hello to there = 1
Shortest path = 0 -> 1
Shortest path distance from hello to here = 1
Shortest path = 0 -> 2
Shortest path distance from about to here = 1
Shortest path = 3 -> 2
The main change I introduced is the code related with the calculation of the start and goal variables:
String[] tokens = line.split(" ");
String start = tokens[0];
String goal = tokens[1];
I assume you are using another text file, perhaps another code; with the one provided the assertion will fail or a StringIndexOutOfBounds exception will be raised when you calculate goal as the substring from index 6 to 11.
Apart from that, the algorithm should work fine.
That being said, please, be aware that you are constructing a graph hyperconnected, in which every node has a direct path to a different node and itself. Maybe that could be your objective, but be aware that things get interesting when you do some other kind of stuff.
For instance, if instead of this code:
for(String word: words) {
for(String word2: words){
g.addEdge(words.indexOf(word), words.indexOf(word2));
}
}
You try something like this:
g.addEdge(words.indexOf("hello"), words.indexOf("there"));
g.addEdge(words.indexOf("hello"), words.indexOf("about"));
g.addEdge(words.indexOf("about"), words.indexOf("here"));
The output of the algorithm has more sense:
Shortest path distance from hello to there = 1
Shortest path = 0 -> 1
Shortest path distance from hello to here = 2
Shortest path = 0 -> 3 -> 2
Shortest path distance from about to here = 1
Shortest path = 3 -> 2
I suppose you are using code from Java Textbook
your code should be
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class words_sof {
public static void main(String[] args) throws IOException {
ArrayList<String> words = new ArrayList<String>();
words.add("hello");
words.add("there");
words.add("here");
words.add("about");
Graph g = new Graph(words.size());
for (String word : words) {
for (String word2 : words) {
g.addEdge(words.indexOf(word), words.indexOf(word2));
}
}
try (BufferedReader readValues = new BufferedReader(new InputStreamReader(new FileInputStream("values.txt")))) {
while (true) {
// ORIGINAL String line = readTestFile.readLine();
// Should be
String line = readValues.readLine();
if (line == null) {
break;
}
// ORIGINAL parse like this is not appropriate
// assert line.length() == 11;
// String start = line.substring(0, 5);
// String goal = line.substring(6, 11);
// Use something like https://stackoverflow.com/questions/20728050/split-strings-in-java-by-words
String [] tokens = line.split("[\\s']");
String start = tokens[0];
String goal = tokens[1];
BreadthFirstPaths bfs = new BreadthFirstPaths(g, words.indexOf(start));
if (bfs.hasPathTo(words.indexOf(goal))) {
// Captions added for clarity
System.out.println("Distance : " + bfs.distTo(words.indexOf(goal)));
for (int v : bfs.pathTo(words.indexOf(goal))) {
System.out.print(" -> " + v);
}
System.out.println();
} else
System.out.println("Nothing");
}
}
}
}
Please notice modifications to the
// ORIGINAL
lines.
The code above yields
Distance : 1
-> 0 -> 1
Distance : 1
-> 0 -> 2
Distance : 1
-> 3 -> 2

display array issues possibly due to whitespace characters

I'm trying to import a txt file with car info and separate the strings into arrays and then display them. The number of doors is combined with the next number plate. Have tried a few ways to get rid of the whitespace characters which I think is causing the issue but have had no luck.
whitespace chars
My code displays this result:
Number Plate : AG53DBO
Car Type : Mercedes
Engine Size : 1000
Colour : (255:0:0)
No. of Doors : 4
MD17WBW
Number Plate : 4
MD17WBW
Car Type : Volkswagen
Engine Size : 2300
Colour : (0:0:255)
No. of Doors : 5
ED03HSH
Code:
public class Application {
public static void main(String[] args) throws IOException {
///// ---- Import File ---- /////
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
reader.close();
String content = stringBuilder.toString();
///// ---- Split file into array ---- /////
String[] dataList = content.split(",");
// Display array
for (String temp : dataList) {
// System.out.println(temp);
}
ArrayList<Car> carArray = new ArrayList();
// Loop variables
int listLength = 1;
int arrayPosition = 0;
// (dataList.length/5)
while (listLength < 5) {
Car y = new Car(dataList, arrayPosition);
carArray.add(y);
listLength++;
arrayPosition += 4;
}
for (Car temp : carArray) {
System.out.println(temp.displayCar());
}
}
}
And
public class Car {
String[] data;
private String modelUnpro;
private String engineSizeUnpro;
private String registrationUnpro;
private String colourUnpro;
private String doorNoUnpro;
// Constructor
public Car(String[] data, int arrayPosition) {
registrationUnpro = data[arrayPosition];
modelUnpro = data[arrayPosition + 1];
engineSizeUnpro = data[arrayPosition + 2];
colourUnpro = data[arrayPosition + 3];
doorNoUnpro = data[arrayPosition + 4];
}
// Getters
private String getModelUnpro() {
return modelUnpro;
}
private String getEngineSizeUnpro() {
return engineSizeUnpro;
}
private String getRegistrationUnpro() {
return registrationUnpro;
}
private String getColourUnpro() {
return colourUnpro;
}
private String getDoorNoUnpro() {
return doorNoUnpro;
}
public String displayCar() {
return "Number Plate : " + getRegistrationUnpro() + "\n Car Type : " + getModelUnpro() + "\n Engine Size : "
+ getEngineSizeUnpro() + "\n Colour : " + getColourUnpro() + "\n No. of Doors : " + getDoorNoUnpro() + "\n";
}
}
Text file:
AG53DBO,Mercedes,1000,(255:0:0),4
MD17WBW,Volkswagen,2300,(0:0:255),5
ED03HSH,Toyota,2000,(0:0:255),4
OH01AYO,Honda,1300,(0:255:0),3
WE07CND,Nissan,2000,(0:255:0),3
NF02FMC,Mercedes,1200,(0:0:255),5
PM16DNO,Volkswagen,1300,(255:0:0),5
MA53OKB,Honda,1400,(0:0:0),4
VV64BHH,Honda,1600,(0:0:255),5
ER53EVW,Ford,2000,(0:0:255),3
Remove Line separator from while loop.
String fileName = "D:\\Files\\a.txt";
BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line.trim());
}
reader.close();
String content = stringBuilder.toString();
String[] dataList = content.split(",");
ArrayList<Car> carArray = new ArrayList();
int listLength = 1;
int arrayPosition = 0;
// (dataList.length/5)
while (listLength < 3) {
Car y = new Car(dataList, arrayPosition);
carArray.add(y);
listLength++;
arrayPosition += 4;
}
for (Car temp : carArray) {
System.out.println(temp.displayCar());
}
In StringBuilder you collect all lines:
AG53DBO,Mercedes,1000,(255:0:0),4\r\nMD17WBW,Volkswagen,2300,(0:0:255),5\r\n...
This string should first be spit on ls - and then you have lines with fields separated by comma.
Now just splitting by comma will cause a doubled array element 4\r\nMD17WBW.
Something like:
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
Path path = Paths.get(fileName);
List<String> lines = Files.readAllLines(path); // Without line ending.
List<Car> cars = new ArrayList<>();
for (String line : lines) {
String[] data = line.split(",");
Car car = new Car(data);
cars.add(car);
}
Path, Paths and especially Files are very handy classes. With java Streams one also can abbreviate things like:
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
Path path = Paths.get(fileName);
List<Car> cars = Files.lines(path) // Stream<String>
.map(line -> line.split(",")) // Stream<String[]>
.map(Car::new) // Stream<Car>
.collect(Collectors.toList()); // List<Car>
Here .lines returns a Stream<String> (walking cursor) of lines in the file, without line separator.
Then .map(l -> l.split(",")) splits every line.
Then the Car(String[]) constructor is called on the string array.
Then the result is collected in a List.

Print out words that are found in an ArrayList but not a file? [duplicate]

This question already has answers here:
String searching algorithms in Java
(5 answers)
Closed 8 years ago.
I have a spell check program that has these containing words:
Mary had a little lambb
Its fleece was white as ssnow
And everywhere that Mary wentt
The lamb was sure to ggo
The lambb, snnow wentt and ggo are purposely spelled like that.
I have written code that prints out the words that ARE found in the dictionary but cannot figure how to print out the words that AREN'T found.
Here is my code so far:
package testDelimeter;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> dict = new ArrayList<String>();
File inFile = new File(
"C:\\Users\\Ceri\\workspace1\\testDelimeter\\src\\testDelimeter\\"
+ "dict" + ".txt");
Scanner in = new Scanner(inFile);
File text = new File(
"C:\\Users\\Ceri\\workspace1\\testDelimeter\\src\\testDelimeter\\"
+ "text" + ".txt");
Scanner s = new Scanner(text);
while(in.hasNext()){
dict.add(in.next());
}
while(s.hasNext()){
String temp = s.next();
for(int i = 0; i < dict.size(); i++){
if(temp.equalsIgnoreCase(dict.get(i))){
System.out.println(dict.get(i) + temp);
}
}
}
}
}
Use a java.util.set for your dictionary. Check if an entry exists using the method .contains(..) of the java.util.collection interface implemented by List and Sets.
You shouldn't use a List as a dictionary because a dictionary has no order and can contain duplicate entries.
The best improvement you can make is changing you List for a Set.
List is intended to be used when order is important and Set is intended to be used for unordered lists of unique elements. As you dictionary contains unique words, Set is better for your case.
Take a look at What is the difference between Set and List?
public static void main(String[] args) throws FileNotFoundException {
Set<String> dict = new HashSet<String>();
File inFile = new File(
"C:\\Users\\Ceri\\workspace1\\testDelimeter\\src\\testDelimeter\\"
+ "dict" + ".txt");
Scanner in = new Scanner(inFile);
File text = new File(
"C:\\Users\\Ceri\\workspace1\\testDelimeter\\src\\testDelimeter\\"
+ "text" + ".txt");
Scanner s = new Scanner(text);
while (in.hasNext()) {
dict.add(in.next().toLowerCase());
}
while (s.hasNext()) {
String temp = s.next().toLowerCase();
if (dict.contains(temp)) {
System.out.println("Found " + temp);
} else {
System.out.println("Not Found " + temp);
}
}
}
Edit: As OP wants to maintain lists, the code can be as follows:
public static void main(String[] args) throws FileNotFoundException {
List<String> dict = new ArrayList<String>();
File inFile = new File(
"C:\\Users\\Ceri\\workspace1\\testDelimeter\\src\\testDelimeter\\"
+ "dict" + ".txt");
Scanner in = new Scanner(inFile);
File text = new File(
"C:\\Users\\Ceri\\workspace1\\testDelimeter\\src\\testDelimeter\\"
+ "text" + ".txt");
Scanner s = new Scanner(text);
while (in.hasNext()) {
// Notice toLowerCase()
dict.add(in.next().toLowerCase());
}
while (s.hasNext()) {
// Notice toLowerCase()
String temp = s.next().toLowerCase();
if (dict.contains(temp)) {
System.out.println("Found " + temp);
} else {
System.out.println("Not Found " + temp);
}
}
}
A quick way to do this would be to introduce a boolean variable as shown below :
boolean isWordFound;
while (s.hasNext()) {
String temp = s.next();
isWordFound = false;
for (int i = 0; i < dict.size(); i++) {
if (temp.equalsIgnoreCase(dict.get(i))) {
isWordFound = true;
System.out.println("Found"+dict.get(i)+temp);
break;
}
}
if (!isWordFound) {
System.out.println("Could not find"+temp);
}
}
That being said, your program is a bit inefficient. Using a Map instead of list is the first change you can make.

Searching for strings in a text file

I was programing in Python but now I want to do the same code in Java. Can you help me please? This is the code that I was working on
import random
import re
a = "y"
while a == "y":
i = input('Search: ')
b = i.lower()
word2 = ""
for letter in b:
lista = []
with open('d:\lista.txt', 'r') as inF:
for item in inF:
if item.startswith(letter):
lista.append(item)
word = random.choice(lista)
word2 = word2 + word
print(word2)
a = input("Again? ")
Now I want to do the same on Java but Im not really sure how to do it. Its not that easy. Im just a beginner. So far I founded a code that makes the search in a text file but I'm stuck.
This is the java code. It finds the position of the word. I've been trying to modify it without the results Im looking for.
import java.io.*;
import java.util.Scanner;
class test {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Search: ");
String searchText = input.nextLine();
String fileName = "lista.txt";
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
while (reader.ready()) {
sb.append(reader.readLine());
}
}
catch(IOException ex) {
ex.printStackTrace();
}
String fileText = sb.toString();
System.out.println("Position in file : " + fileText.indexOf(searchText));
}
}
What I want is to find an item in a text file, a list, but just want to show the items that begin with the letters of the string I want to search. For example, I have the string "urgent" and the text file contains:
baby
redman
love
urban
gentleman
game
elephant
night
todd
So the display would be "urban"+"redman"+"gentleman"+ until it reaches the end of the string.
Let's assume that you've already tokenized the string so you've got a list of Strings, each containing a single word. It's what comes from the reader if you've got one word per line, which is how your Python code is written.
String[] haystack = {"baby", "redman", "love", "urban", "gentleman", "game",
"elephant", "night", "todd"};
Now, to search for a needle, you can simply compare the first characters of your haystack to all characters of the needle :
String needle = "urgent";
for (String s : haystack) {
for (int i = 0; i < needle.length(); ++i) {
if (s.charAt(0) == needle.charAt(i)) {
System.out.println(s);
break;
}
}
}
This solutions runs in O(|needle| * |haystack|).
To improve it a bit for the cost of a little bit of extra memory, we can precompute a hash table for the available starts :
String needle = "urgent";
Set<Character> lookup = new HashSet<Character>();
for (int i = 0; i < needle.length(); ++i) {
lookup.add(needle.charAt(i));
}
for (String s : haystack) {
if (lookup.contains(s.charAt(0))) {
System.out.println(s);
}
}
The second solution runs in O(|needle| + |haystack|).
This works if your list of words isn't too large. If your list of words is large you could adapt this so that you stream over the file multiple time collecting words to use.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class Test {
public static void main(String[] args) {
Map<Character, List<String>> map = new HashMap<Character, List<String>>();
File file = new File("./lista.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
// assumes words are space separated with no
// quotes or commas
String[] tokens = line.split(" ");
for(String word : tokens) {
if(word.length() == 0) continue;
// might as well avoid case issues
word = word.toLowerCase();
Character firstLetter = Character.valueOf(word.charAt(0));
List<String> wordsThatStartWith = map.get(firstLetter);
if(wordsThatStartWith == null) {
wordsThatStartWith = new ArrayList<String>();
map.put(firstLetter, wordsThatStartWith);
}
wordsThatStartWith.add(word);
}
}
Random rand = new Random();
String test = "urgent";
List<String> words = new ArrayList<String>();
for (int i = 0; i < test.length(); i++) {
Character key = Character.valueOf(test.charAt(i));
List<String> wordsThatStartWith = map.get(key);
if(wordsThatStartWith != null){
String randomWord = wordsThatStartWith.get(rand.nextInt(wordsThatStartWith.size()));
words.add(randomWord);
} else {
// text file didn't contain any words that start
// with this letter, need to handle
}
}
for(String w : words) {
System.out.println(w);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(reader != null) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
This assumes the content of lista.txt looks like
baby redman love urban gentleman game elephant night todd
And the output will look something like
urban
redman
gentleman
elephant
night
todd

Read a text file and store numbers in different arrays in java

I am currently writing my thesis, and in that context I need to develop a meta-heuristic using java. However I am facing a problem when trying to read and store the data.
My file is a text file, with around 150 lines. An example of the problem is in line 5 where three integer numbers are stated: 30, 38 and 1. I would like to store each of these as an integer called respectively L, T and S, and this goes on for many other of the lines.
Any of you who knows how to do that? If needed I can send you the txt file.
btw: this is what I've tried so far:
Main.java:
import java.io.IOException;
import java.io.FileWriter;
import java.io.BufferedWriter;
public class MAIN {
public static void main(String[] args) throws IOException {
Test.readDoc("TAP_T38L30C4F2S12_03.txt");
}
}
Test.java:
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Test {
private static ArrayList<Integer> integerList = new ArrayList<Integer>();
public static Map<String, ArrayList<Integer>> data = new HashMap<String, ArrayList<Integer>>();
public static String aKey;
public static void readDoc(String File) {
try{
FileReader fr = new FileReader("TAP_T38L30C4F2S12_03.txt");
BufferedReader br = new BufferedReader(fr);
while(true) {
String line = br.readLine();
if (line == null)
break;
else if (line.matches("\\#\\s[a-zA-Z]")){
String key = line.split("\\t")[1];
line = br.readLine();
data.put(key, computeLine(line));
}
else if (line.matches("\\\\\\#\\s(\\|[a-zA-Z]\\|,?\\s?)+")){
String[] keys = line.split("\\t");
line = br.readLine();
ArrayList<Integer> results = computeLine(line);
for (int i=0; i<keys.length; i++){
aKey = aKey.replace("|", "");
// data.put(aKey, results.get(i));
data.put(aKey, results);
}
}
System.out.println(data);
}
} catch(Exception ex) {
ex.printStackTrace(); }
}
private static ArrayList<Integer> computeLine (String line){
String[] splitted = line.split("\\t");
for (String s : splitted) {
integerList.add(Integer.parseInt(s));
}
return integerList;
}
}
And example of the data is seen here:
\# TAP instance
\# Note that the sequence of the data is important!
\#
\# |L|, |T|, |S|
30 38 1
\#
\# v
8213 9319 10187 12144 8206 ...
\#
\# w
7027 9652 9956 13973 6661 14751 ...
\#
\# b
1 1 1 1 1 ...
\#
\# c
1399 1563 1303 1303 2019 ...
\#
\# continues
The following code is working with the sample data you gave.
In short :
Create a field to store your data, I chose a TreeMap so you can map a letter to a certain number of Integers but you can use another Collection.
Read the file line by line using BufferedReader#readLine()
Then process each bunch of lines depending on your data. Here I use regular expressions to match a given line and then to remove everything that is not data. See String#split(), String#matches()
But before all start by reading some good beginners books about java and Object Oriented Design.
public class ReadAndParse {
public Map<String, ArrayList<Integer>> data = new TreeMap<String, ArrayList<Integer>>();
public ReadAndParse() {
try {
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
while(true) {
String line = br.readLine();
if (line == null) break;
else if (line.matches("\\\\#\\s[a-zA-Z]")){
String key = line.split("\\s")[1];
line = br.readLine();
ArrayList<Integer> value= computeLine(line);
System.out.println("putting key : " + key + " value : " + value);
data.put(key, value);
}
else if (line.matches("\\\\\\#\\s(\\|[a-zA-Z]\\|,?\\s?)+")){
String[] keys = line.split("\\s");
line = br.readLine();
ArrayList<Integer> results = computeLine(line);
for (int i=1; i<keys.length; i++){
keys[i] = keys[i].replace("|", "");
keys[i] = keys[i].replace(",", "");
System.out.println("putting key : " + keys[i] + " value : " + results.get(i-1));
ArrayList<Integer> value= new ArrayList<Integer>();
value.add(results.get(i-1));
data.put(keys[i],value);
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
// print the data
for (Entry<String, ArrayList<Integer>> entry : data.entrySet()){
System.out.println("variable : " + entry.getKey()+" value : "+ entry.getValue() );
}
}
// the compute line function
private ArrayList<Integer> computeLine(String line){
ArrayList<Integer> integerList = new ArrayList<>();
String[] splitted = line.split("\\s+");
for (String s : splitted) {
System.out.println("Compute Line : "+s);
integerList.add(Integer.parseInt(s));
}
return integerList;
}
// and the main function to call it all
public static void main(String[] args) {
new ReadAndParse();
}
}
Some sample output of what I got after parsing your file :
variable : L value : [30]
variable : S value : [1]
variable : T value : [38]
variable : b value : [1, 1, 1, 1, 1]
variable : c value : [1399, 1563, 1303, 1303, 2019]
variable : v value : [8213, 9319, 10187, 12144, 8206]
variable : w value : [7027, 9652, 9956, 13973, 6661, 14751]
I think I've got something.
EDIT:
I've changed my approach
You'll need to import;
import java.io.BufferedReader;
Then
BufferedReader reader = new BufferedReader
int[] arr = new int[3];
int L;
int T;
int S;
for (int i = 0 ;i<5; i++){ //brings you to fifth line
line = reader.readLine();
}
L = line.split(" ")[0]trim();
T = line.split(" ")[1]trim();
S = line.split(" ")[2]trim();
arr[0] = (L);
arr[1] = (T);
arr[2] = (S);

Categories