Insertion into Hash Map data structure JAVA - java

I am using a program to read keywords in a file and sort them on basis of frequency. I am using Map data structure for the same.
But i am facing problem, even if i have repeated entries, their count is not increased. Thus if a word is repeated in the file it is stored in a different place in the data structure rather than incrementing value of the previous entry in the maps. Please find my code below. That is what i tried. Also i am making sure if a match is "" or " " it is not stored in the hash map still it is counted.
Pattern p = Pattern.compile("[a-zA-Z]*",Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(handlerContent);
while(m.find() ) //&& (m.group().length()>1)
{
boolean blnExists = keyword_counts.containsValue(m.group());
if(blnExists==true)
{
if(m.group()!="" || m.group()!=" ")
{
System.out.println("Repeat");
keyword_counts.put(m.group(), keyword_counts.get(m.group()+1));
System.out.println(m.group()+" "+keyword_counts.get(m.group()) );
}
}
else
{
if(m.group()!="" || m.group()!=" ")
{
keyword_counts.put(m.group(), 1);
System.out.println(m.group()+" "+keyword_counts.get(m.group()) );
}
}
}

Your test should probably be:
keyword_counts.containsKey(m.group());
And you should use equals to compare strings instead of == or != but that is not the reason for your issue.

in Java "=" should not be used with strings. use the "equals" method instead.

in your statement boolean blnExists = keyword_counts.containsValue(m.group());
you are check for the value instead of the key.
try this:
boolean blnExists = keyword_counts.containsKey(m.group());
and use if(m.group() != null && !"".equals(m.group().trim())) instead of
if(m.group()!="" || m.group()!=" ")

Related

How to strip ' \n' in Java?

I have the following piece of code:
String name='ishtiaq\n'
How can I strip the newline-character?
Thank you in advance.
If the "\n" always occurs at the end, use String.trim() [this won't remove the period, however, if you care about doing that]. If you want to eliminate internal newlines, you could use String.replaceAll(). You could also copy the string into a StringBuilder or array to construct a new string, skipping over the elements you wish to discard, or you could locate the relevant indices and use substring() to get a substring that excludes the elements you don't like. In short, there are many ways to do this.
Here is just one of many ways to do it (this one removing both the period symbol and the newline):
private static String nameWithoutSuffix(String nameWithSuffix) {
int periodIndex = nameWithSuffix.indexOf('.');
int newlineIndex = nameWithSuffix.indexOf('\n');
if ((periodIndex == -1) && (newlineIndex == -1)) {
return nameWithSuffix;
}
int suffixStartIndex = -1;
if (periodIndex != -1) {
suffixStartIndex = periodIndex;
}
if ((newlineIndex != -1)
&& ((suffixStartIndex == -1)
|| (newlineIndex < suffixStartIndex))) {
suffixStartIndex = newlineIndex;
}
return nameWithSuffix.substring(0, suffixStartIndex);
}
Java Strings have .replace!
With it, your problem becomes super easy:
String strippedString = name.replace("\n", "");
Remember: When you use replace, Java won't work on the existing String. That's why you'll have to store the return-value in another object. (You could use the same of course.)

Finding if a specific character exists at a specific index

so I'm trying to figure out how to create a condition for my decision structure. I'm making a program that converts military time to conventional time. When times are entered, they must be in a XX:XX format, where X equals a digit. I'm wondering, how can I make a validation that checks to make sure that ":" always exists as a colon and is in the same spot?
myString.charAt(5) == ':'
Just change 5 to whatever you need, and check string length before you do this, so you don't ask for something past the end of a short string.
You could search the string with indexOf(), which returns the index at which the character is found. This will check if a colon is in the string and if it's in the right position.
if("10:00".indexOf(':') == 2)
// do something
It will return -1 if the value is not found. Check out the java documentation for more information.
Here is the answer for it
Suppose you had string that contains XX:XX
yourString="XX:XX"
yourString.contains(":") - return true - if exists
":" takes the 3rd position. So it will be 2(0,1,2)
yourString.charAt(2) == ':'
Together , it will be
if(yourString.contains(":") && yourString.charAt(2) == ':'){
//your logic here
}else{
something here
}
Here is one approach to that,
String[] test = new String[] { "00:00", "NN:NN", "12,13", "12:13" };
for (String fmt : test) {
boolean isValid = true;
for (int i = 0; i < fmt.length(); i++) {
char c = fmt.charAt(i);
if (i == 2) {
if (c != ':') { // here is the colon check.
isValid = false;
break;
}
} else {
// This checks for digits!
if (!Character.isDigit(c)) {
isValid = false;
break;
}
}
}
System.out.println(fmt + " is " + isValid);
}
Output is
00:00 is true
NN:NN is false
12,13 is false
12:13 is true
#WillBro posted a good answer but I give you another option:
myString.indexOf(":") == 5
With indexOf you can also look for full String inside a String.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
But for string format validations I suggest you to use Regular Expresions.
Here's a full example that does what you want to do:
http://www.mkyong.com/regular-expressions/how-to-validate-time-in-24-hours-format-with-regular-expression/

How do I link a user input argument with a string?

So, I'm rather new to Java and I just starting a project, but I ran into some issues.
My question is... How do I link a user input (argument) with a String?
I have already defined a few Strings earlier on in my code, but in this line I want it to match up and check from the String which matches the argument and check if it contains something:
if (!cs.hasPermission("foo." + args[0]) && [CODE HERE] ){
I want [CODE HERE] to check If args[0] (user input) matches a String, if it does then check if it matches some text.
Java has a .equals() method which can be used to compare two Strings. It can used to compare two variables which hold references to String objects or to compare String literals
if( args[0].equals(someString) ) { // compare args[0] to another String variable
}
if( "someText".equals(args[0]) ) { // compare args[0] to a String literal
}
Reading through the String documentation will also be very useful to you starting out.
This is String equals api, so it should look something like:
if (!cs.hasPermission("foo." + args[0]) && args[0].equals(string){
//code
}
You can easily do it with the equals() method. But you should also check that args[0] is set.
if (args.length > 0) {
if (!cs.hasPermission("foo." + args[0]) && "StringToCompare".equals(args[0])) {
// do something
}
} else {
// handle error
}

Multiple arguments for !somearray.contains

Is it possible to have multiple arguments for a .contains? I am searching an array to ensure that each string contains one of several characters. I've hunted all over the web, but found nothing useful.
for(String s : fileContents) {
if(!s.contains(syntax1) && !s.contains(syntax2)) {
found.add(s);
}
}
for (String s : found) {
System.out.println(s); // print array to cmd
JOptionPane.showMessageDialog(null, "Note: Syntax errors found.");
}
How can I do this with multiple arguments? I've also tried a bunch of ||s on their own, but that doesn't seem to work either.
No, it can't have multiple arguments, but the || should work.
!s.contains(syntax1+"") || !s.contains(syntax2+"") means s doesn't contain syntax1 or it doesn't contain syntax2.
This is just a guess but you might want s contains either of the two:
s.contains(syntax1+"") || s.contains(syntax2+"")
or maybe s contains both:
s.contains(syntax1+"") && s.contains(syntax2+"")
or maybe s contains neither of the two:
!s.contains(syntax1+"") && !s.contains(syntax2+"")
If syntax1 and syntax2 are already strings, you don't need the +""'s.
I believe s.contains("") should always return true, so you can remove it.
It seems that what you described can be done with a regular expression.
In regular expression, the operator | marks you need to match one of several choices.
For example, the regex (a|b) means a or b.
The regex ".*(a|b).*" means a string that contains a or b, and other then that - all is OK (it assumes one line string, but that can be dealt with easily as well if needed).
Code example:
String s = "abc";
System.out.println(s.matches(".*(a|d).*"));
s = "abcd";
System.out.println(s.matches(".*(a|d).*"));
s = "fgh";
System.out.println(s.matches(".*(a|d).*"));
Regular Exprsssions is a powerful tool that I recommend learning. Have a look at this tutorial, you might find it helpful.
There is not such thing as multiple contains.
if you require to validate that a list of string is included in some other string you must iterate through them all and check.
public static boolean containsAll(String input, String... items) {
if(input == null) throw new IllegalArgumentException("Input must not be null"); // We validate the input
if(input.length() == 0) {
return items.length == 0; // if empty contains nothing then true, else false
}
boolean result = true;
for(String item : items) {
result = result && input.contains(item);
}
return result;
}

Java .getText vs. Hard Coded String not returning the same results

I am completely stumped with this one . . .
If I call the function below with the following:
Search(SearchTextField.getText()); // (Fiberglass was entered)
Search("Fiberglass"); // hardcoded
I get the following results:
Fiberglass 10 Not Here
Fiberglass 10 String found!
Same String is passed with the same length, different results. How can this be?
Yes I've trimmed it on both sides of the == with no luck.
I am loosing my mind, any help would be appreciated.
Test[] array = new Test[3];
array[0] = new RowBoat("Wood", "Oars", 10);
array[1] = new PowerBoat("Fiberglass", "Outboard", 35);
array[2] = new SailBoat("Composite", "Sail", 40);
public void Search(String searchString) {
boolean found = false;
System.out.print(searchString + " " + searchString.length() + " ");
for (int i = 0; i < array.length; i++) {
if (searchString == array[i].getBoatMaterial()) {
found = true;
break;
}
}
if (found) {
System.out.println("String found!");
} else {
System.out.println("Not Here");
}
}
Use the .equals() method when you're comparing Strings. Do not use ==
equals() will compare the actual String content, no matter where the String resides in memory.
if (searchString.equals(array[i].getBoatMaterial())) {
Since String variables are references in Java, when you code
if (searchString == array[i].getBoatMaterial()) {
What you are actually doing is comparing two pointers. It just so happens that when you hardcode the same string in multiple places in your program the compiler reduces it to one instance (since Strings are immutable) and reuses it. This is why using a hardcoded value succeeds, since both pointers point to the same value. However, when the search string is not the same hardcoded "Fiberglass", the two strings are at different locations and the comparison fails. To compare two strings use the String.equals(String) method instead.
Use the String.equals(String other) function to compare strings, not the == operator.
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal.

Categories

Resources