I have a long text which is stored in a String (i.e. tstr1 im code). Now I want to store the user input from console in a String[] (i.e. itemsFromArray im code).
I want for each word stored in the user input String[] array, the system to show how many times that word is present in the long Text String[] array. I tried in this way, but the problem is that the system shows the count just for first entry from an array but for the next it is showing zero.
btnNewButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
keyW = txtKeyword.getText();
search = textField.getText();
System.out.println("String for car = " + search);
System.out.println("String keyword = " + keyW);
WebDriver driver = new FirefoxDriver();
driver.get("https://en.wikipedia.org/wiki/" + search);
tstr1 = driver.findElement(By.xpath("//*[#id='content']")).getText();
String [] itemsFromArray = keyW.split(",");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String word : itemsFromArray){
map.put(word, 0);
}
Scanner s = new Scanner(tstr1);
while (s.hasNext()){
String word = s.next();
if (map.containsKey(word)){
map.put(word, map.get(word) + 1);
System.out.println("Word1 '" + word + "' count:" + map.get(word));
} else {
System.out.println("Word2 '" + word + "' not in map");
}
}
driver.close();
}
});
It's probably better to use a Map<String, Integer>:
// initialize a mapping that is used to map words to their count
Map<String, Integer> counter = new HashMap<String, Integer>();
// initialize all counts to 0
for (String word : itemsFromArray){
counter.put(word, 0);
}
// ...
// count words that are in map (give up those that aren't)
while (s.hasNext()){
String word = s.next();
if (counter.containsKey(word)){
counter.put(word, counter.get(word) + 1);
System.output.println("Word '" + word + "' count:" + counter.get(word));
} else {
System.output.println("Word '" + word + "' not in map");
}
}
After I spent one day, the problem was that when I tried to separate the string (without comma) and insert into array, the first string was good but the next started with white spaces and the system does not recognize the word.
btnNewButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//If the button UPLOAD was not pressed we should to clear the ArrayList
listKeys.clear();
//////////////////////////////////////////////
if(textField.getText().equals("")) {
JOptionPane.showMessageDialog(null,"Make sure you enter at least one search key");
}
else if (txtKeyword.getText().equals("")) {
System.out.println("String is NULL ");
JOptionPane.showMessageDialog(null,"Add at least one keyword");
} else {
keyW = txtKeyword.getText();
search = textField.getText();
System.out.println("String for car = " + search);
System.out.println("String keyword = " + keyW);
WebDriver driver = new FirefoxDriver();
driver.get("https://en.wikipedia.org/wiki/" + search);
tstr1 = driver.findElement(By.xpath("//*[#id='content']")).getText();
String [] items = keyW.split(",");
String [] itemsFromArray = new String[items.length];
for ( int i = 0; i < items.length; i++)
{
itemsFromArray[i] = items[i].trim();
}
for(String string : itemsFromArray)
{
//if (args[i].toLowerCase().startsWith( "from:" ))
System.out.println("FOREACH " + string);
int i = countWords(tstr1, string);
System.out.println("Word count "+ string + ": " + i);
Keyword1 = ("Count for word " + string + " are " + i);
listKeys.add(Keyword1);
}
driver.close();
}
}
private static int countWords(String tstr1, String string)
{
int i = 0;
Scanner s = new Scanner(tstr1);
while (s.hasNext())
{
if (s.next().equals(string))
i++;
}
return i;
}
}
Related
so I'm having a small problem in java. I have something like
"Victor Fleming"
"Gone With"
"With The"
"The Wind."
So what the sentence should actually look like is
"Victor Fleming"
"Gone with the wind."
Therefore I'm looking to form a single sentence, by words that are adjacent and the same. If no adjacent same word is detected then the sentence will be separated as in "Victor Fleming" case where Fleming is not the same with Gone, so a new sentence is starting. What I've written so far:
List<String> separatedText = new ArrayList<>();
int i = 0;
while (i < mergedTextByHeightColor.size()) {
if ((i < (mergedTextByHeightColor.size() - 3)) && !(mergedTextByHeightColor.get(i + 1).equals(mergedTextByHeightColor.get(i + 2)))) {
separatedText.add(mergedTextByHeightColor.get(i) + " " + mergedTextByHeightColor.get(i + 1));
i = i + 2;
}
String concatStr = "";
while ((i < (mergedTextByHeightColor.size() - 3)) && (mergedTextByHeightColor.get(i + 1).equals(mergedTextByHeightColor.get(i + 2)))) {
if (concatStr.contains(mergedTextByHeightColor.get(i))) {
concatStr = mergedTextByHeightColor.get(i + 1) + " " + mergedTextByHeightColor.get(i + 3);
} else {
concatStr = mergedTextByHeightColor.get(i) + " " + mergedTextByHeightColor.get(i + 1) + " " + mergedTextByHeightColor.get(i + 3);
}
i = i + 3;
}
separatedText.add(concatStr);
}
We can store the sentences in a String array, then loop through each one.
Inside the loop, we check whether the last word of the last item (by splitting it into an array with .split(" "), then getting the last element) is equal to the first word of the current item. If it is, we first remove the first word of the current item, then append it to a StringBuilder.
If it isn't, then we append the StringBuilder's value to the list, append the current element, and move on.
String[] sentences = {"Victor Fleming", "Gone With", "With The", "The Wind."};
List<String> newsentences = new ArrayList<>();
StringBuilder str = new StringBuilder();
for(int i = 0; i < sentences.length; i++) {
String cur = sentences[i];
if(i != 0) {
String[] a = sentences[i-1].split(" ");
String[] b = cur.split(" ");
String last = a[a.length-1];
String first = b[0];
if(last.equalsIgnoreCase(first)) {
str.append(cur.substring(first.length()));
}else {
newsentences.add(str.toString());
str = new StringBuilder();
str.append(cur);
}
}else {
str.append(cur);
}
}
newsentences.add(str.toString());
System.out.println(Arrays.toString(newsentences.toArray()));
Output:
[Victor Fleming, Gone With The Wind.]
I am trying to figure out how to make a grep method that can read wrapped phrases from up-to infinity lines(That is a sentence or string spanning multiple lines of a given text file) in java. Here is my current code for the grep function:
public static void grep() throws IOException{
BufferedReader f = new BufferedReader(new FileReader("Cabbages.txt"));
Scanner in = new Scanner(System.in);
String line = "", input = "", wrappedPhrase = "", modified = "";
int c = 0, foundCount = 0;
boolean found = false;
System.out.print("Please enter something you want to grep: ");
input = in.nextLine();
while((line = f.readLine()) != null) {
c++;
found = false;
int index = line.indexOf(input);
while(index >= 0) {
modified = "<" + line.substring(line.indexOf(input), (line.indexOf(input)+input.length())) + ">";
found = true;
index = line.indexOf(input, index + 1);
foundCount++;
}
if(found) {
System.out.println("Found on line: " + c + ", which is: " + line.replace(input, modified));
}
}
if(foundCount <= 0) {
System.out.println("Sorry, the input string of: \"" + input + "\" was not found within the given file.");
}else {
System.out.println("In total, the input string of: \"" + input + "\"" + " was found " + foundCount + " time(s).");
}
}
Hi guys this is my first post in this website and I'm still new to Java. This my code that i am working on.
public static void main(String[] args) throws Exception {
// debug
if ($DEBUG) System.out.println("starting\n");
//read data from text file into arrays w,p
String[] wArr = new String[50];
String[] pArr = new String[50];
String fileName = "homs.txt";
readFile(fileName, wArr, pArr);
//main control loop
while (true) {
//use input dialog to get 2 words from user
String input = JOptionPane.showInputDialog(null,"Enter two words: ");
String[] words = input.split("\\s+");
String w1 = words[0];
String w2 = words[1];
//check each word if in dictionary
int w1ix = chkFound(wArr, w1);
boolean isFound = (w1ix >= 0);
System.out.println(w1 + " is found: " + isFound);
int w2ix = chkFound(wArr, w2);
boolean isFound2 = (w2ix >= 0);
System.out.println(w2 + " is found: " + isFound2);
if (w1ix >=0 && w2ix >=0 ) msg = "both words " + w1 + " and " + w2 +
"\n\tare in dictionary";
else { msg = "one or more words not in dictionary: ";
if (w1ix <0) msg += w1 + " ";
if (w2ix <0) msg += w2 + " ";
System.out.println(msg);
//check if homonyms
boolean isHom = chkHom(pArr, w1, w2);
//output result
String line = msg +
"\nWord 1: " + w1 +
"\nWord 2: " + w2 +
"\nWord 1 in dictionary: " + isFound +
"\nWord 2 in dictionary: " + isFound2 +
"\nHomonyms: " + isHom;
JOptionPane.showMessageDialog(null, line);
//ask user to continue Y/N?
int cont = JOptionPane.showConfirmDialog(null, "Continue?");
if (cont > 0)
break;//exit loop or continue
}
//end main
}
}
public static int chkFound(String[] wArr, String w) {
for (String a : wArr) {
if(a.equals(w))
return 1;
}
return -1;
}//end chkFound
My problem for this code is that when i run it it keeps looping
String input = JOptionPane.showInputDialog(null,"Enter two words: ");
I think the reason for this problem is this part of the code. I have not come up with a solution for this though.
public static int chkFound(String[] wArr, String w) {
for (String a : wArr) {
if(a.equals(w))
return 1;
}
return -1;
}//end chkFound
https://docs.oracle.com/javase/7/docs/api/constant-values.html#javax.swing.JOptionPane.OK_OPTION
public static final int OK_OPTION 0
your break doesn't work
if (cont > 0)
break;//exit loop or continue
change it to:
final int cont = JOptionPane.showConfirmDialog(null, "Continue?","Continue?", JOptionPane.YES_NO_OPTION);
if(cont == JOptionPane.NO_OPTION){
break;
}
I made a code for my system which would update a record in my text file database but I cant seem to make it work. The code doesnt have any error. its just not doing what I intend it to do
public static void Update() throws Exception {
File tempfile2 = new File("temp.txt");
tempfile2.createNewFile();
FileInputStream tempFStream = new FileInputStream(tempfile2);
BufferedReader read = new BufferedReader(new InputStreamReader(tempFStream));
System.out.print("Product Number: ");
String searchnum = br.readLine();
try {
LoadFile();
boolean found = false;
for (int i = 0; i < row; i++) {
String record[] = list.get(i).split(",");
if (!searchnum.equals(record[0])) {
found = true;
FileWriter fw = new FileWriter(tempfile2, true);
fw.write(record[0] + "," + record[1] + "," + record[2] + "," + record[3] + "," + record[4] + "," + record[5] + "\r\n");
fw.close();
}
}
for (int i = 0; i < row; i++) {
String record[] = list.get(i).split(",");
if (searchnum.equals(record[0])) {
found = true;
System.out.println("\t\t\t*******************************");
System.out.println("\t\t\t PIXBOX PHOTOBOOTH");
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\tRecord Found:");
System.out.println("\n\t\t\tProduct Number : " + record[0]);
System.out.println("\t\t\tCategory : " + record[1]);
System.out.println("\t\t\tProduct Name : " + record[2]);
System.out.println("\t\t\tPrice [m/d/y] : " + record[3]);
System.out.println("\t\t\tQuantity : " + record[4]);
System.out.println("\n\n\t\t\t--------------------------------");
System.out.print("\t\t\tAre you sure you want to replace the records?<Y/N>: ");
String del = br.readLine();
if (del.equals("Y") || del.equals("y")) {
LoadFile();
System.out.println("\t\t\t*******************************");
System.out.println("\t\t\t PIXBOX PHOTOBOOTH");
System.out.println("\t\t\t*******************************");
System.out.println("\n\n\t\t\t------Update Record Form------");
System.out.print("\n\n\t\t\tProduct Number : ");
int prodnum = Integer.parseInt(br.readLine());
System.out.print("\t\t\tCategory : ");
String cat = br.readLine();
System.out.print("\t\t\tProduct Name :");
String prodname = br.readLine();
System.out.print("\t\t\tPrice: ");
String price = br.readLine();
System.out.print("\t\t\tQuantity : ");
String quan = br.readLine();
read.close();
database.delete();
boolean rename = false;
if (rename = tempfile2.renameTo(database)) {
InsertRecords(prodnum, cat, prodname, price, quan);
System.out.println("\t\t\tSuccessfully Edited!");
exiting();
} else {
System.out.print("Edit Failed!");
}
} else if (del.equals("N") || del.equals("n")) {
MainMenu();
}
}
if (!searchnum.equals(record[1])) {
System.out.println("\n\t\t\tNo Record Found.");
Thread.sleep(2000);
exiting();
}
}
} catch (Exception e) {
System.out.print("File Empty!");
}
}
public static void LoadFile()throws Exception
{
list.clear();
FileInputStream fis = new FileInputStream(database);
BufferedReader read = new BufferedReader(new InputStreamReader(fis));
row = 0;
while(read.ready())
{
list.add(read.readLine());
row++;
}
read.close();
}
Everytime I run this... it would work until Product Number: User input and after entering a number it would directly display File is empty which is at the end of the program. its as if the try/catch is ignored. I definitely did something wrong but I dont know what I did wrong. Anyone shed me some light? Thanks
and with the e.printStackTrace(); here's what displayed after entering a product number...
java.lang.ArrayIndexOutofBoundException:5
at SnackTimeInventorySystem.Update<SnackTimeInventorySystem.java:525>
at SnackTimeInventorySystem.MainMenu<SnackTimeInventorySystem.java:66>
at SnackTimeInventorySystem.Login<SnackTimeInventorySystem.java:369>
at SnackTimeInventorySystem.main<SnackTimeInventorySystem.java:14>
Turns out I only had 5 entries on my array but declared 6 entries to be written
System.out.println("\t\t\t*******************************");
System.out.println("\t\t\t PIXBOX PHOTOBOOTH");
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\tRecord Found:");
System.out.println("\n\t\t\tProduct Number : " + record[0]);
System.out.println("\t\t\tCategory : " + record[1]);
System.out.println("\t\t\tProduct Name : " + record[2]);
System.out.println("\t\t\tPrice [m/d/y] : " + record[3]);
System.out.println("\t\t\tQuantity : " + record[4]);
System.out.println("\n\n\t\t\t--------------------------------");
fw.write(record[0] + "," + record[1] + "," + record[2] + "," + record[3] + "," + record[4] + "," + record[5] + "\r\n");
So I just had to delete record[5] and fixed the problem thanks to Tom
I want to search object inside arraylist get value from user input and print it to text area. here is the code.
//the arrayList I declared
Book[]myBook = new Book [30];
int index = 0;
private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {
String title = titleTF.getText();
boolean found = false;
for (int i = 0; i < index; i++) {
if (myBook[i].getTitle().equals(title));
{
outputTA.append("Book Title : " + myBook[i].getTitle() + "\n");
outputTA.append("Book Author : " + myBook[i].getAuthor() + "\n");
outputTA.append("Year of Publication : " + myBook[i].getYear() + "\n");
outputTA.append("Book Status : " + myBook[i].getStatus() + "\n");
outputTA.append("======================================\n");
found = true;
break;
}
}
if (found == false) {
JOptionPane.showMessageDialog(this, "Book is not Found! Please Try again!");
}
}
The problem is, when I click the search button, it will display the first object in the arraylist. Which line of code is wrong?
First off, your index is 0 so your for doesn't loop. Replace index with myBook.size()