I have a Java program that works without issue for searching most strings but for some reason I am unable to have it find the below ina file which I know appears in the file. I am obviously trying to locate a certain element that has the value of 999 but i am unable to do so. Again this works for other strings just not the one below.
for(int i=0;i< inputFile.length;i++)
try {
br = new BufferedReader(new FileReader(inputFile[i]));
try {
while((line = br.readLine()) != null)
{
countLine++;
//System.out.println(line);
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(inputSearch)) {
count++;
countBuffer++;
}
}
if(countBuffer > 0)
{
countBuffer = 0;
lineNumber += countLine + ",";
}
}
br.close();
If I understand your question, you could use a Pattern and Matcher and something like -
String toMatch = "<element>999</element>";
Pattern pattern = Pattern.compile(">\\s*999\\s*<");
Matcher match = pattern.matcher(toMatch);
int count = 0;
int start = 0;
while (start < toMatch.length() && match.find(start)) {
// Pattern found.
start = match.regionEnd() + 1;
count++;
}
Related
I would like to count countX and countX using the same loop instead of creating three different loops. Is there any easy way approaching that?
public class Absence {
private static File file = new File("/Users/naplo.txt");
private static File file_out = new File("/Users/naplo_out.txt");
private static BufferedReader br = null;
private static BufferedWriter bw = null;
public static void main(String[] args) throws IOException {
int countSign = 0;
int countX = 0;
int countI = 0;
String sign = "#";
String absenceX = "X";
String absenceI = "I";
try {
br = new BufferedReader(new FileReader(file));
bw = new BufferedWriter(new FileWriter(file_out));
String st;
while ((st = br.readLine()) != null) {
for (String element : st.split(" ")) {
if (element.matches(sign)) {
countSign++;
continue;
}
if (element.matches(absenceX)) {
countX++;
continue;
}
if (element.matches(absenceI)) {
countI++;
}
}
}
System.out.println("2. exerc.: There are " + countSign + " rows int the file with that sign.");
System.out.println("3. exerc.: There are " + countX + " with sick note, and " + countI + " without sick note!");
} catch (FileNotFoundException ex) {
Logger.getLogger(Absence.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
text file example:
# 03 26
Jujuba Ibolya IXXXXXX
Maracuja Kolos XXXXXXX
I think you meant using less than 3 if statements. You can actually so it with no ifs.
In your for loop write this:
Countsign += (element.matches(sign)) ? 1 : 0;
CountX += (element.matches(absenceX)) ? 1 : 0;
CountI += (element.matches(absenceI)) ? 1 : 0;
Both answers check if the word (element) matches all regular expressions while this can (and should, if you ask me) be avoided since a word can match only one regex. I am referring to the continue part your original code has, which is good since you do not have to do any further checks.
So, I am leaving here one way to do it with Java 8 Streams in "one liner".
But let's assume the following regular expressions:
String absenceX = "X*";
String absenceI = "I.*";
and one more (for the sake of the example):
String onlyNumbers = "[0-9]*";
In order to have some matches on them.
The text is as you gave it.
public class Test {
public static void main(String[] args) throws IOException {
File desktop = new File(System.getProperty("user.home"), "Desktop");
File txtFile = new File(desktop, "test.txt");
String sign = "#";
String absenceX = "X*";
String absenceI = "I.*";
String onlyNumbers = "[0-9]*";
List<String> regexes = Arrays.asList(sign, absenceX, absenceI, onlyNumbers);
List<String> lines = Files.readAllLines(txtFile.toPath());
//#formatter:off
Map<String, Long> result = lines.stream()
.flatMap(line-> Stream.of(line.split(" "))) //map these lines to words
.map(word -> regexes.stream().filter(word::matches).findFirst()) //find the first regex this word matches
.filter(Optional::isPresent) //If it matches no regex, it will be ignored
.collect(Collectors.groupingBy(Optional::get, Collectors.counting())); //collect
System.out.println(result);
}
}
The result:
{X*=1, #=1, I.=2, [0-9]=2}
X*=1 came from word: XXXXXXX
#=1 came from word: #
I.*=2 came from words: IXXXXXX and Ibolya
[0-9]*=2 came from words: 03 and 06
Ignore the fact I load all lines in memory.
So I made it with the following lines to work. It escaped my attention that every character need to be separated from each other. Your ternary operation suggestion also nice so I will use it.
String myString;
while ((myString = br.readLine()) != null) {
String newString = myString.replaceAll("", " ").trim();
for (String element : newString.split(" ")) {
countSign += (element.matches(sign)) ? 1 : 0;
countX += (element.matches(absenceX)) ? 1 : 0;
countI += (element.matches(absenceI)) ? 1 : 0;
I have a CSV file with the following information:
2,Cars
5,Cars
5,Planes
5,Boats
10,Planes
10,Boats
28,Planes
I want to split the numbers from the type of transportation. How can I count the total of cars + planes + boats to be '3' and not '7'?
I am using the following Java code that someone else provided to split the CSV:
try {
BufferedReader br2 = new BufferedReader(new FileReader("transport.csv"));
System.out.println("\nTESTING");
String sCurrentLine2;
java.util.HashMap<String, String>();
while ((sCurrentLine2 = br2.readLine()) != null) {
String[] information2 = sCurrentLine2.split(",");
String transCode = information2[1];
System.out.println(transCode);
}
} catch (IOException e) {
e.printStackTrace();
}
In the array String transCode = information2[1]; when I change to 0 it will give the numbers, when I change to 1 gives the names.
while((sCurrentLine2 = br2.readLine()) != null{
String[] entries = sCurrentLine2.split(",");
Set<String> types = new Hashset<>();
for(int i = 0; i < entries.length; i++){
String[] entry = entries[i].split(" ");
types.add(entry[0]);
}
System.out.println(types.size());
}
I modified the code you provided. Maybe there is another way to do it better, but this is what I did. I forced it a little and gave '3' as result. But it should have done it counting the words not considering duplicated.
while ((line2 = br2.readLine()) != null) {
String[] entries = line2.split(",");
for (int i = 0; i < entries.length; i++) {
String[] entry = entries[i].split(" ");
termsDup.add(entry[0]);
}
}
System.out.println(termsDup.size()-4);
I am new to Java Strings.
Actually I have the code to reverse words:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test2 {
public static void main(String[] args) throws IOException
{
System.out.println("enter a sentence");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String rev =br.readLine();
String [] bread = rev.split(" ");
for(int z =bread.length-1;z>=0;z--)
{
System.out.println(bread[z]);
}
}
}
For the above code I get:
Input :Bangalore is a city
Output: City is a Bangalore
But I want the output to be like below:
Input: Bangalore is a city
Output:cityaisba ng a lore
Another Example:
Input: Hello Iam New To Java.Java is object Oriented language.
Output: langu age Ori en tedo bjec ti sjava. javaToNe wIamolleH
Please help me out
Here is one way you could do it:
String rev = br.readLine();
String [] bread = rev.split(" ");
int revCounter = 0;
for(int z = bread.length - 1; z >= 0; z--)
{
String word = bread[z];
for(int i = 0; i < word.length(); i++)
{
// If char at current position in 'rev' was a space then
// just print space. Otherwise, print char from current word.
if(rev.charAt(revCounter) == ' ')
{
System.out.print(' ');
i--;
}
else
System.out.print(word.charAt(i));
revCounter++;
}
}
When I run your code I get following result:
city
a
is
Bangalore
So to have it in a single line, why don't you add a space and print a single line?
System.out.println("enter a sentence");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String rev = br.readLine();
String[] bread = rev.split(" ");
for (int z = bread.length - 1; z >= 0; z--) {
System.out.print(bread[z] + " ");
}
I didn't check the validity of your code like GHajba did. But if you want spaces to remain on specific places it might be an option to remove all spaces and put them back according to their index in the original String.
Remove all
newBread = newBread.replace(" ", "");
Put them back
StringBuilder str = new StringBuilder(newBread);
for (int index = oldBread.indexOf(" ") ;
index >= 0 ;
index = oldBread.indexOf(" ", index + 1))
{
str.insert(index, ' ');
}
newBread = str.toString();
I came up with this quick and there might be better ways to do this, maybe without StringBuilder, but this might help you until you find a better way.
Try with this (i've used a string as input):
String original = "Bangalore is a city";
System.out.println("Original : "+original);
StringBuilder inverted = new StringBuilder();
StringBuilder output = new StringBuilder();
String temp = "";
String[] split = original.split("\\s+");
for (int i = split.length - 1; i >= 0; i--) {
inverted.append(split[i]);
}
temp = inverted.toString();
for (String string : split) {
int currLenght = string.length();
String substring = temp.substring(0,currLenght);
temp = temp.replaceAll(substring, "");
output.append(substring).append(" ");
}
System.out.println("Converted : "+output.toString());
Append the reversed words without the spaces into a StringBuffer.
StringBuffer b = new StringBuffer();
for (int i = bread.length-1; i >= 0 ; i--) {
b.append(bread[i]);
}
Then insert the spaces of the original String into the StringBuffer.
int spaceIndex, prevIndex = 0;
while ((spaceIndex = rev.indexOf(" ", prevIndex + 1)) != -1) {
b.insert(spaceIndex, ' ');
prevIndex = spaceIndex;
}
Am I reading the following input correctly?
Here is my code so far:
while ((line = br.readLine()) != null) {
line = line.substring(line.indexOf('[')+1, line.indexOf(']'));
String[] parts = line.split(",");
for (int i = 0; i< parts.length; i++) {
rangeNo[i]= Integer.parseInt(parts[i]);
System.out.println("{" + rangeNo[i] + "}");
}
}
and this is my input
[2,9], [3,11]
Also, when I try to print the value of rangeNo[3] it return 0 instead of 3
can someone help me out with this?
Do you expect [2,9], [3,11] to be in one line or two separate lines?
If its supposed to be one line then you might want to try something like this
Integer rangeNo[] = new Integer[10];
String line = "[2,9], [3,11]";
line = line.replace('[', ' ');
line = line.replace(']', ' ');
String[] parts = line.split(",");
for (int i = 0; i < parts.length; i++) {
rangeNo[i] = Integer.parseInt(parts[i].trim());
System.out.println("{" + rangeNo[i] + "}");
}
when you check here
line = line.substring(line.indexOf('[')+1, line.indexOf(']'));
it's matching first condition. i.e works fine for [2,9] not after that thus only 2 and 9 are getting stored here.
String[] parts = line.split(",");
so
parts[0]=2
parts[1]=9
parts[2]=0
I am working on a code-editor in java and i want to know how to auto-indent using brackets (open and close) like an actual code editor .
like this 1:
Array PrincipalVar = (Var => (OtherVar => (var3 => 3,
var4 => 8,
var6 => 1)
),
Var2 => (var => 1))
Editor is a JEditorPane. I tried some code, but nothing seem to work.
I have already file contening code, and I want to Re-Indent this file.
Code I already tried :
public String indentFileTry() throws FileNotFoundException{
LinkedList<Integer> inBracket = new LinkedList<Integer>();
String currentLine = "";
Scanner indent = new Scanner(new FileReader(f));
String ptu = "";
while(indent.hasNextLine()) {
currentLine = indent.nextLine();
currentLine = currentLine.trim();
char[] line = currentLine.toCharArray();
int i = 0;
while(i < line.length){ //Here I define the position of the Bracet for Indentation
if(line[i] == '('){
inBracket.addFirst(i);
}
i++;
}
if(!inBracket.isEmpty()){//here I indent with the position of the bracket and I remove the first(First In First Out)
if(!currentLine.contains(")")){
int spaceadded = 0;
String space ="";
while(spaceadded <= inBracket.getFirst()){
spaceadded++; space += " ";
}
currentLine = space + currentLine;
inBracket.removeFirst();
}else if(currentLine.contains(")")){
int spaceadded = 0;
String space ="";
while(spaceadded <= inBracket.getFirst()){
spaceadded++; space += " ";
}
currentLine = space + currentLine;
inBracket.removeFirst();
}
}
ptu += currentLine +"\n";
}
indent.close() ;
System.out.println(ptu);
return ptu;
}
If you expect automatically indentation you won't get such code. You should implement it yourself adding \n spaces (or \t) chars to format your code. JEditorPane does not understand your code logic. You (with your code parser) should define parent/child relation for lines of code you have.
One example for the case when parent/children are defined is XML. See the XMLEditorKit where nodes are indented.
For the response, What I do is easy.
I made a LinkedList, and I use it like a FILO (First in Last out) like this :
public String indentFile() throws FileNotFoundException{
LinkedList<Integer> positionBracket = new LinkedList<Integer>();
String currentLine = "";
Scanner indent = new Scanner(new FileReader(f));
String stringIndented = "";
while(indent.hasNextLine()) {
currentLine = indent.nextLine();
currentLine = currentLine.trim();
char[] lineInChar = currentLine.toCharArray();
int i = 0;
int spaceadded = 0;
String space ="";
if(!positionBracket.isEmpty()){
while(spaceadded <= positionBracket.getFirst()){
spaceadded++;
space += " "; // We put same space like the last opened bracket
}
}
while(i < lineInChar.length){
if(lineInChar[i] == '('){ //If opened bracket I put the position in the top of the Filo
positionBracket.addFirst(new Integer(i));
}
if(lineInChar[i] == ')' && !countCom){
positionBracket.removeFirst(); //If closed bracket I remove the position on the top of the Filo
}
i++;
}
stringIndented += space + currentLine +"\n";
}
}
return stringIndented;
}