How can i use splitter ^ in java - java

I have a problem with my java program. I have to read lines from a file, the form of these lines is:
1#the^cat#the^dog#the^bird#^fish#bear
2#the^cat#the^dog#the^bird#^fish#bear
and print all, accept the "#" and "^" at textfields in my GUI. The "^" must appear in case there in not article. For exaple ^fish, i have to print it as ^fish but the^dog i have to print the dog.
As far i can read and print the lines in the textfields but i can't find a way to skip the "^" between the words.
Here is my code:
try {
FileReader file = new FileReader("C:\\Guide.txt");
BufferedReader BR = new BufferedReader(file);
boolean eof = false;
int i=0;
while (!eof) {
String line = BR.readLine();
if (line == null)
eof = true;
else {
i++;
System.out.println("Parsing line "+i+" <"+line+">");
String[] words = line.split("#");
if (words.length != 7) continue;
number=words[0];
onomastiki=words[1];
geniki=words[2];
aitiatiki=words[3];
klitiki=words[4];
genos=words[5];
Region=words[6];
E = new CityEntry(number,onomastiki,geniki,
aitiatiki,klitiki,
genos,Region);
Cities.add(E);
}

You can try something like this.
FileReader file = new FileReader("C:\\\\Users\\\\aq104e\\\\Desktop\\\\text");
BufferedReader BR = new BufferedReader(file);
boolean eof = false;
int i = 0;
while (!eof) {
String line = BR.readLine();
if (line == null)
eof = true;
else {
i++;
System.out.println("Parsing line " + i + " <" + line + ">");
String[] words = line.split("#");
for (int j = 0; j < words.length; j++) {
if(words[j].contains("^")) {
if(words[j].indexOf("^") == 0) {
// write your code here
//This is case for ^fish
}else {
// split using ^ and do further manipulations
}
}
}
}
}
Let me know if this works for you.

That is gonna work, but it is not best way)
foreach(String word : words){
if(word.contains"the"){
word.replace("^"," ");
}
}

Related

Split lines with "," and do a trim on every element [duplicate]

This is some code that I found to help with reading in a 2D Array, but the problem I am having is this will only work when reading a list of number structured like:
73
56
30
75
80
ect..
What I want is to be able to read multiple lines that are structured like this:
1,0,1,1,0,1,0,1,0,1
1,0,0,1,0,0,0,1,0,1
1,1,0,1,0,1,0,1,1,1
I just want to essentially import each line as an array, while structuring them like an array in the text file.
Everything I have read says to use scan.usedelimiter(","); but everywhere I try to use it the program throws straight to the catch that replies "Error converting number". If anyone can help I would greatly appreciate it. I also saw some information about using split for the buffered reader, but I don't know which would be better to use/why/how.
String filename = "res/test.txt"; // Finds the file you want to test.
try{
FileReader ConnectionToFile = new FileReader(filename);
BufferedReader read = new BufferedReader(ConnectionToFile);
Scanner scan = new Scanner(read);
int[][] Spaces = new int[10][10];
int counter = 0;
try{
while(scan.hasNext() && counter < 10)
{
for(int i = 0; i < 10; i++)
{
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = scan.nextInt();
}
}
}
for(int i = 0; i < 10; i++)
{
//Prints out Arrays to the Console, (not needed in final)
System.out.println("Array" + (i + 1) + " is: " + Spaces[i][0] + ", " + Spaces[i][1] + ", " + Spaces[i][2] + ", " + Spaces[i][3] + ", " + Spaces[i][4] + ", " + Spaces[i][5] + ", " + Spaces[i][6]+ ", " + Spaces[i][7]+ ", " + Spaces[i][8]+ ", " + Spaces[i][9]);
}
}
catch(InputMismatchException e)
{
System.out.println("Error converting number");
}
scan.close();
read.close();
}
catch (IOException e)
{
System.out.println("IO-Error open/close of file" + filename);
}
}
I provide my code here.
public static int[][] readArray(String path) throws IOException {
//1,0,1,1,0,1,0,1,0,1
int[][] result = new int[3][10];
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
Scanner scanner = null;
line = reader.readLine();
if(line == null) {
return result;
}
String pattern = createPattern(line);
int lineNumber = 0;
MatchResult temp = null;
while(line != null) {
scanner = new Scanner(line);
scanner.findInLine(pattern);
temp = scanner.match();
int count = temp.groupCount();
for(int i=1;i<=count;i++) {
result[lineNumber][i-1] = Integer.parseInt(temp.group(i));
}
lineNumber++;
scanner.close();
line = reader.readLine();
}
return result;
}
public static String createPattern(String line) {
char[] chars = line.toCharArray();
StringBuilder pattern = new StringBuilder();;
for(char c : chars) {
if(',' == c) {
pattern.append(',');
} else {
pattern.append("(\\d+)");
}
}
return pattern.toString();
}
The following piece of code snippet might be helpful. The basic idea is to read each line and parse out CSV. Please be advised that CSV parsing is generally hard and mostly requires specialized library (such as CSVReader). However, the issue in hand is relatively straightforward.
try {
String line = "";
int rowNumber = 0;
while(scan.hasNextLine()) {
line = scan.nextLine();
String[] elements = line.split(',');
int elementCount = 0;
for(String element : elements) {
int elementValue = Integer.parseInt(element);
spaces[rowNumber][elementCount] = elementValue;
elementCount++;
}
rowNumber++;
}
} // you know what goes afterwards
Since it is a file which is read line by line, read each line using a delimiter ",".
So Here you just create a new scanner object passing each line using delimter ","
Code looks like this, in first for loop
for(int i = 0; i < 10; i++)
{
Scanner newScan=new Scanner(scan.nextLine()).useDelimiter(",");
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = newScan.nextInt();
}
}
Use the useDelimiter method in Scanner to set the delimiter to "," instead of the default space character.
As per the sample input given, if the next row in a 2D array begins in a new line, instead of using a ",", multiple delimiters have to be specified.
Example:
scan.useDelimiter(",|\\r\\n");
This sets the delimiter to both "," and carriage return + new line characters.
Why use a scanner for a file? You already have a BufferedReader:
FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);
Now you can read the file line by line. The tricky bit is you want an array of int
int[][] spaces = new int[10][10];
String line = null;
int row = 0;
while ((line = reader.readLine()) != null)
{
String[] array = line.split(",");
for (int i = 0; i < array.length; i++)
{
spaces[row][i] = Integer.parseInt(array[i]);
}
row++;
}
The other approach is using a Scanner for the individual lines:
while ((line = reader.readLine()) != null)
{
Scanner s = new Scanner(line).useDelimiter(',');
int col = 0;
while (s.hasNextInt())
{
spaces[row][col] = s.nextInt();
col++;
}
row++;
}
The other thing worth noting is that you're using an int[10][10]; this requires you to know the length of the file in advance. A List<int[]> would remove this requirement.

Array doesn't retain its value after being written to

I'm trying to read a file into an array, each line will be store in an index of the array. Given the following input in the text.txt file :
6afe
5af
3eafe
7fae
3sfs
1eef
I read into the array, then printout the array in the console to check, but somehow the array doesn't retain its value after the loop. The output I got was null, before and after, but not in middle of the loop. Please tell me why ? Thank you
Here are the output I get
nullline 0
nullline four
6afe
5af
3eafe
7fae
3sfs
1eef
nullline three
nullline four
The output I epxected to get are :
nullline 0 // array still empty here, i get it
nullline four // array still empty
6afe
5af
3eafe
7fae
3sfs
1eef
7fae // where here are null three ? in the actual ouput
3sfs // null three ?
And here is my code :
import java.io.*;
public class readSortWrite
{
public static void main(String[] args) throws java.io.IOException
{
//input file
// to count lineNum
FileReader fr = new FileReader("text.txt");
BufferedReader br = new BufferedReader(fr);
//to read into array names[]
FileReader fr1 = new FileReader("text.txt");
BufferedReader br1 = new BufferedReader(fr1);
// output file
FileWriter fw = new FileWriter("sorted.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
// counting number of line
int lineNum = 0;
String line;
line = br.readLine();
while(line != null)
{
lineNum++;
line = br.readLine();
}
pw.close();
// System.out.println(lineNum + "lines");
// create an array of of lineNum size and write each line of file into array
String[] names = new String[lineNum];
String str;
str = br1.readLine();
System.out.println(names[0]+ " line 0");
System.out.println(names[4] + " line four");
for (int i = 0 ; i<lineNum; i++)
{
while (str!= null)
{
names[i] = str;
str = br1.readLine();
System.out.println(names[i]);
}
}
// fr1.close();
System.out.println(names[3]+ " line three");
System.out.println(names[4] + " line four");
}
}
first 2 lines are null cause you create the array and print the values at 0 and 4 indices before init them, like so
String[] names = new String[lineNum];
String str;
str = br1.readLine();
System.out.println(names[0]+ " line 0");
System.out.println(names[4] + " line four");
for the second last rows, the while loop will read the buffer till it empty but without any iteration of the for loop, thus only populated names[0]
for (int i = 0 ; i<lineNum; i++)
{
while (str!= null)
{
names[i] = str;
str = br1.readLine();
System.out.println(names[i]);
}
}
change it to something like
int i =0;
while (str!= null && i < lineNum) {
names[i] = str;
str = br1.readLine();
System.out.println(names[i]);
}
The error lies in the nested loops used to read the file into array
for (int i = 0 ; i<lineNum; i++)
{
while (str!= null)
{
names[i] = str;
str = br1.readLine();
System.out.println(names[i]);
}
}
so for the first value of i you read The entire input file. when you wxit the nested while loop, the entire file has been read, but the index remained the same.
yuo should have one loop that reads the file, and the index is advanced at each iteration
int i = 0;
while (str!= null)
{
names[i] = str;
i++;
str = br1.readLine();
System.out.println(names[i]);
}
You declare and instantiate names:
String[] names = new String[lineNum];
but after that you haven't put anything into names when you try to print:
System.out.println(names[0]+ " line 0");
System.out.println(names[4] + " line four");
In the for loop that follows you are overwriting names[0] repeatedly. The while loop executes using 0 as the value of i.
Just replace it with the code below. You were using a while true
String str;
System.out.println(names[0]+ " line 0");
System.out.println(names[4] + " line four");
for (int i = 0 ; i<lineNum; i++)
{
str = br1.readLine();
if (str!= null)
{
names[i] = str;
System.out.println(names[i]);
}
}
String[] names = new String[lineNum];
String str;
str = br1.readLine();
System.out.println(names[0]+ " line 0");
System.out.println(names[4] + " line four");
the code you just create names[], so output is null.
for (int i = 0 ; i<lineNum; i++)
{
while (str!= null)
{
names[i] = str;
str = br1.readLine();
System.out.println(names[i]);
}
}
the code ,when i=0 ,you enter while and not break,so System.out.println(names[i]); always output names[0] until the last str.
and names[] other element is always null.

How to ignore duplicate strings when using RegEx to match string?

EDIT: editted for clarity as to what I'm having trouble with. I'm not getting the right responses as its counting dupes. I HAVE to use RegEx, can use tokenizer however but I did not.
What I am trying to do here is, there is 5 input files. I need to calculate how many "USER DEFINED VARIABLES" there are. Please ignore the messy code, I'm just learning Java.
I replaced: everything within ( and ), all non-word characters, any statements such as int, main etc, any digit with a space infront of it, and any blank space with a new line then trim it.
This leaves me with a list that has a variety of strings which I will match with my RegEx. However, at this point, how make my count only include unique identifiers?
EXAMPLE:
For example, in the input file I have attached beneath the code, I am receiving
"distinct/unique identifiers: 10" in my output file, when it should be "distinct/unique identifiers: 3"
And for example, in the 5th input file I have attached, I should have "distinct/unique identifiers: 3" instead I currently have "distinct/unique identifiers: 6"
I cannot use Set, Map etc.
Any help is great! Thanks.
import java.util.*
import java.util.regex.*;
import java.io.*;
public class A1_123456789 {
public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.out.println("Wrong number of arguments");
System.exit(1);
}
for (int i = 0; i < args.length; i++) {
FileReader jk = new FileReader(args[i]);
BufferedReader ij = new BufferedReader(jk);
FileWriter fw = null;
BufferedWriter bw = null;
String regex = "\\b(\\w+)(\\s+\\1\\b)+";
Pattern p = Pattern.compile("[_a-zA-Z][_a-zA-Z0-9]{0,30}");
String line;
int count = 0;
while ((line = ij.readLine()) != null) {
line = line.replaceAll("\\(([^\\)]+)\\)", " " );
line = line.replaceAll("[^\\w]", " ");
line = line.replaceAll("\\bint\\b|\\breturn\\b|\\bmain\\b|\\bprintf\\b|\\bif\\b|\\belse\\b|\\bwhile\\b", " ");
line = line.replaceAll(" \\d", "");
line = line.replaceAll(" ", "\n");
line = line.trim();
Matcher m = p.matcher(line);
while (m.find()) {
count++;
}
}
try {
String s1 = args[i];
String s2 = s1.replaceAll("input","output");
fw = new FileWriter(s2);
bw = new BufferedWriter(fw);
bw.write("distinct/unique identifiers: " + count);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
if (fw != null) {
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
//This is the 3rd input file below.
int celTofah(int cel)
{
int fah;
fah = 1.8*cel+32;
return fah;
}
int main()
{
int cel, fah;
cel = 25;
fah = celTofah(cel);
printf("Fah: %d", fah);
return 0;
}
//This is the 5th input file below.
int func2(int i)
{
while(i<10)
{
printf("%d\t%d\n", i, i*i);
i++;
}
}
int func1()
{
int i = 0;
func2(i);
}
int main()
{
func1();
return 0;
}
Try this
LinkedList dtaa = new LinkedList();
String[] parts =line.split(" ");
for(int ii =0;ii<parts.length;ii++){
if(ii == 0)
dtaa.add(parts[ii]);
else{
if(dtaa.contains(parts[ii]))
continue;
else
dtaa.add(parts[ii]);
}
}
count = dtaa.size();
instead of
Matcher m = p.matcher(line);
while (m.find()) {
count++;
}
Amal Dev has suggested a correct implementation, but given the OP wants to keep Matcher, we have:
// Previous code to here
// Linked list of unique entries
LinkedList uniqueMatches = new LinkedList();
// Existing code
while ((line = ij.readLine()) != null) {
line = line.replaceAll("\\(([^\\)]+)\\)", " " );
line = line.replaceAll("[^\\w]", " ");
line = line.replaceAll("\\bint\\b|\\breturn\\b|\\bmain\\b|\\bprintf\\b|\\bif\\b|\\belse\\b|\\bwhile\\b", " ");
line = line.replaceAll(" \\d", "");
line = line.replaceAll(" ", "\n");
line = line.trim();
Matcher m = p.matcher(line);
while (m.find()) {
// New code - get this match
String thisMatch = m.group();
// If we haven't seen this string before, add it to the list
if(!uniqueMatches.contains(thisMatch))
uniqueMatches.add(thisMatch);
}
}
// Now see how many unique strings we have collected
count = uniqueMatches.size();
Note I haven't compiled this, but hopefully it works as is...

Read in a text file 1 line at a time and split the words into an Array Java

The user selects a text file. I take the file and split 1 line into individual words. I then take an if statement to see if one of the words is equal to the word "the". There is the word "the" in the first line however it's not saying there is.IT IS picking up other "the"s just not the very first one (yes I know this is a mess, but it's what I'm working with at the moment)
try {
BufferedReader br = new BufferedReader(new FileReader(test));
//String text = "";
String line = br.readLine();
//while (line != null)
if(line != null) {
for(int j = 0; j < 20; j++) //loops through first 20 lines {
if(line != null) {
//text += line;
String[] words = line.toLowerCase().split(" ");
for(int i = 0; i < words.length; i++){//loops array of split up words
if(words[i].equals("the")) {
System.out.println("Found T H E");
} else {
System.out.println("Didn't find the");
System.out.println(words[i]);
}
line = br.readLine();
}
} else {
System.out.println("");
}
}
} else {
System.out.println("It's null");
}
br.close();
} catch (Exception ex) {
System.err.println("Error" + ex);
}
Try moving the line
line = br.readLine();
outside of the loop
for(int i = 0; i < words.length; i++){

How do I provide null to BufferedReader's readLine() method using Eclipse

public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
String line;
try {
while( (line = in.readLine()) != null ) {
System.out.println(line);
lineCount++;
charCount += line.length();
String[] words = line.split("\\W");
wordCount += words.length;
}
System.out.println("charCount = " + charCount);
System.out.println("wordCount = " + wordCount);
System.out.println("lineCount = " + lineCount);
} catch (IOException e) {
e.printStackTrace();
}
}
Straight to the point: How do I exit the above while-loop? I've read on another question that readLine() returns null when there is no more line left to read, but how do I do that using Eclipse's console?
The only way I can manage to break the loop is to add in cases, such as
if(line.length() == 2 || line.equals("exit")))
break;
if you just want to read a line, why do you need while loop?
or if you want multiple inputs to be taken then you should specify how many inputs are to be taken in first readline();
otherwise i hope below code will resolve your issue :)
public class TestRandomArray {
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
try {
String line = in.readLine();
lineCount++;
charCount += line.length();
String[] words = line.split(" ");
wordCount += words.length;
System.out.println("charCount = " + charCount);
System.out.println("wordCount = " + wordCount);
System.out.println("lineCount = " + lineCount);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Categories

Resources