String loop issue - java

below is my code that checks the incoming model and modifies the source accordingly, checking if its ALLCAPS or Firstcap. The problem I am having is when the model contains a symbol e.g. matchCase("I'm","apple"). This would return apple, when it's supposed to return Apple. On the other hand, If I use "Im", it modifies it correctly to "Apple". Is there a way i can modify it that would work. I tried to run a few methods but I keep getting stuck
public static String matchCase(String model, String source){
boolean o = true;
if(model.toUpperCase().equals(model)){
source = source.toUpperCase();
}
if(Character.isUpperCase(model.charAt(0))){
for(int i=1;i<model.length();i++){
if(Character.isLowerCase(model.charAt(i)) == false){
o = false;
}
}
// if(o == model.length()-1){
if(o == true){
String can = "";
for(int j=0;j<source.length();j++){
if(j==0){
can += Character.toUpperCase(source.charAt(j)); }
else{
can += source.charAt(j);
}
}
source = can;
// Character.toUpperCase(source.charAt(0));
}
}
return source;
}
}

I think your problem comes from the fact that
Character.isLowerCase('\'') // is false
You should change this test
if(Character.isLowerCase(model.charAt(i)) == false)
By
if(Character.isUpperCase(model.charAt(i)))

If you know your model is always going to be either uppercase or firstcap can't you do something like this:
public static String matchCase(String model, String source){
if(model.toUpperCase() == model)
return source.toUpperCase();
// capitalize the first letter of source and send back
return Character.toUpperCase(source.charAt(0)) + source.substring(1);
}

Related

hashCode override in Java returns null when using hashmap and getting newly created objects

I am currently learning about Java's hashcode via MOOC and followed their tutorial. However, expected output returns null when there clearly is a value inside hashmap. My code for override is following:
public class Plate{
private final String regCode;
private final String country;
// Counstructors
...
// accessors... only showing name for less clutter
getCode()
getCountry()
#Override // toString
public String toString(){
return country + " " + regCode;
}
#Override // equals
public boolean equals(Object obj){
if(obj == null){
return false;
}
if(getClass() != obj.getClass()){
return false;
}
Plate cmp = (Plate) obj;
if(this.country.equals(cmp.getCountry())){
return false;
}
if(this.regCode == null || this.regCode.equals(cmp.getCode())){
return false;
}
return true;
}
///////////////////////////////////// Below code may be the problem ///////////////////////////////////
#Override // hashCode
public int hashCode(){
if(this.country == null || this.regCode == null){
return 7;
}
return this.country.hashCode() + this.regCode.hashCode();
}
}
and my main function that uses above code is:
import java.util.ArrayList;
import java.util.HashMap;
public class Regi{
public static void main(String[] args){
Plate reg1 = new Plate("FI", "ABC-123");
Plate reg2 = new Plate("FI", "UXE-465");
Plate reg3 = new Plate("D", "B WQ-431");
ArrayList<Plate> finnish = new ArrayList<Plate>();
finnish.add(reg1);
finnish.add(reg2);
Plate newPlate = new Plate("FI", "ABC-123");
if(!finnish.contains(newPlate)){
finnish.add(newPlate);
}
System.out.println("Finnish " + finnish);
// where unexpected result occur
HashMap<Plate, String> owners = new HashMap<Plate, String>();
owners.put(reg1, "Arto");
owners.put(reg3, "Jurgen");
System.out.println("Owners:");
System.out.println(owners.get(reg1));
System.out.println(owners.get(new Plate("FI", "ABC-123")));
System.out.println(owners.get(new Plate("D", "B WQ-431")));
}
}
Where expected output is:
but my output displays null below "owners:" portion whenever I ran System.out.println(owners.get(new Plate("FI", "ABC-123"))); and System.out.println(owners.get(new Plate("D", "B WQ-431")));. I'm not sure what is wrong with my custom hashCode function since I was able to print out both of my hashCode for country and regCode and they both gave numeric values. I also referenced someone else's post regarding to hashcode to use prime number but it was still displaying null. I was wondering if anyone can point me to right direction regarding to hashCode.
Your code doesn't work, because you make equals return false when the two object have the same country. Or the same regCode:
if(this.country.equals(cmp.getCountry())){
return false;
}
if(this.regCode == null || this.regCode.equals(cmp.getCode())){
return false;
}
You're missing the ! (NOT) operator:
if (! this.country.equals(cmp.getCountry())) {
return false;
}
if (this.regCode == null || ! this.regCode.equals(cmp.getCode())) {
return false;
}
Also, your hashCode() implementation implies that country can be null, so you're missing the null-check:
if (this.country == null || ! this.country.equals(cmp.getCountry())) {
return false;
}

All combinations of alphanumeric string, better way?

The input to the "alphaNumeric" function is a String which consists of alphanumeric characters that are all lower case, for example "hello123hello". I want to be able to check all upper/lower case letter combinations for this string through a check( ) function. (Eg. HeLlO123hELlo is one of the combinations to be checked). I have written code in Java to do this where I store the matching String into an ArrayList, but would like to know if there a better way to do this without the ArrayList. Also, am I correct in saying the worst case runtime of this is O(2^n)? Note: Check is a function that returns either true or false, depending on whether the correct String is passed to the function.
public static String alphaNumeric(String input) {
ArrayList<String> list = new ArrayList<String>();
alphaHelper(input, "", list);
return list.get(0);
}
private static void alphaHelper(String in, String current, ArrayList<String> list) {
if (in.length() == 0) {
if (check(current)) {
list.add(current);
}
} else if (Character.isLetter(in.charAt(0))) {
alphaHelper(in.substring(1),current+in.substring(0,1).toLowerCase(),list);
alphaHelper(in.substring(1),current+in.substring(0,1).toUpperCase(),list);
} else if (Character.isDigit(in.charAt(0))) {
alphaHelper(in.substring(1),current+in.substring(0,1),list);
} else {
return;
}
}
If you just want to remove the ArrayList without changing your basic algorithm, you can do this:
public static String alphaNumeric(String input) {
return alphaHelper(input, "");
}
private static String alphaHelper(String in, String current) {
String result = null;
if (check(current)) {
result = current;
} else if (Character.isLetter(in.charAt(0))) {
result = alphaHelper(in.substring(1),current+in.substring(0,1).toLowerCase());
if (result == null) result = alphaHelper(in.substring(1),current+in.substring(0,1).toUpperCase());
} else if (Character.isDigit(in.charAt(0))) {
result = alphaHelper(in.substring(1),current+in.substring(0,1));
}
return result;
}
Yes it is O(2^n), and I can't see offhand how you would improve on that if you can't get the original string directly.
If you don't need to check substrings (i.e. you only care about case variations of the entire string) you could improve the algorithm by not testing the substrings, but it would still be O(2^n).
You could temporarily set both the check and input to lowercase and compare them then.
public static boolean alphaNumeric(String input, String check) {
return input.toLowerCase().equals(check.toLowerCase());
}
-Sean

Why does Eclipse tell me that this is dead code?

I'm trying to create a recall program that sends text messages to 200+ people and then searches an email that the replies are forwarded too.
This method is supposed to search the array list of replies that is built using another method, but it doesn't work correctly. It will only work if the very first message on the array list matches the very first number in the contact list.
Those are some other problems, but my main question here is why does it say that the code specifically inside of my for loop is dead code?
public static boolean searchForPhone(String phone){
CharSequence phoneN = phone;
for(int i=0;i<myMessages.size();i++){
if(myMessages.get(i).contains(phone)){
return true;
}
else{
return false;
}
}
return false;
}
This is your code, properly formatted:
public static boolean searchForPhone(String phone) {
for (int i = 0; i < myMessages.size(); i++) {
if (myMessages.get(i).contains(phone)) {
return true;
} else {
return false;
}
}
return false;
}
The construct flagged as Dead code is the i++ in the for-loop header. It is indeed dead code because the for loop's body unconditionally makes the method return. Therefore the "step" part of the for header is unreachable aka. dead.
The same fact makes your code perform incorrectly, BTW. Removing the else clause would be a big improvement.
Will this help?
public static boolean searchForPhone(String phone){
CharSequence phoneN = phone;
for(int i=0;i<myMessages.size();i++){
if(myMessages.get(i).contains(phone)){
return true;
}
}
return false;
}
Look you are looping over n-element list. When you get first element on the list you got if/else statement.
So you will HAVE TO either of 2 things, both of witch is return. So your program will exit on first element returned.
To make it simplier, your code is equal to:
CharSequence phoneN = phone;
if (myMessages.size() ==0 ){
return false;
}
return myMessages.get(0).contains(phone);
Try from Window > Preferences > Java > Compiler > Error/Warnings
Change Dead code (e.g 'if(false)') and Unnecessary 'else' statement to Error.
Your loop always returns from the function at the end of the first iteration. This makes i++ dead code since it never executes.
Anyway, remove the else clause to fix the code.
In the else part you need to continue to search. Else if your fist element is not the matching one will return false and not going to check other element.
public static boolean searchForPhone(String phone) {
CharSequence phoneN = phone;
for (int i = 0; i < myMessages.size(); i++) {
if (myMessages.get(i).contains(phone)) {
return true;
} else {
//return false this conditional return cause
// the complain it as dead code. Since for loop will become not
//loop
continue; // will search for other elements.
}
}
return false;
}
Now you can simplify this code to following because else part is not really necessary.
public static boolean searchForPhone(String phone) {
CharSequence phoneN = phone;
for (int i = 0; i < myMessages.size(); i++) {
if (myMessages.get(i).contains(phone)) {
return true;
}
}
return false;
}

Java return statement

Eclipse keeps telling me to add a return statement to the method, even though I did so.
public class PrefixCode {
public String isOne(String[] words) {
if(words.length==1) {
return "Yes";
}
ArrayList<Integer> indexPositions= new ArrayList<Integer>();
for(int i=0;i<words.length;i++) {
String firstWord=words[i];
java.util.List<String> listOfWordsToCheck = new ArrayList<String>(Arrays.asList(words));
listOfWordsToCheck.set(i,null);
for(int j=0;j<listOfWordsToCheck.size();j++) {
String secondWord= listOfWordsToCheck.get(j);
if(firstWord.startsWith(secondWord)==true) {
indexPositions.add(j);
}
else if(firstWord.startsWith(secondWord)==false);
}
}
if(indexPositions.size()==0) {
return "Yes";
}
else if(indexPositions.size()!=0) {
Collections.sort(indexPositions);
return "No,"+indexPositions.get(0)+"";
}
}
}
My return statements are outside of the for loops, so I don't understand what's wrong here.
There is no default return. The only returns you are making are if some conditions are true. What if the conditions are false?
Add a return after the last else block and you are all good to go.
The else block is redundant. What lies inside the else block should be be without else.
Since you have added if, else if, you need to else to that control flow to satisfy the compiler. Logically, size can be either zero or more than zero. So, you need to have if and else part only
if(indexPositions.size()==0){
return "Yes";
} else if(indexPositions.size()!=0){
Collections.sort(indexPositions);
return "No,"+indexPositions.get(0)+"";
} else {
// return what?
}
You can simplify this logic by,
if(indexPositions.size() == 0) {
return "Yes";
} else { //size more than zero
Collections.sort(indexPositions);
return "No,"+indexPositions.get(0) + "";
}
you should use else instead of
else if(indexPositions.size() != 0) {
Collections.sort(indexPositions);
return "No,"+indexPositions.get(0) + "";
}
The compiler doesn't know if the if conditions are going to succeed. So, you need to add a default return out of those if (even if your if conditions cover all possible cases!)
One of the best practice is to have only one return at the method end! Like this:
public String isOne(String[] words) {
String isOne = null;
if(words.length==1){
isOne = "Yes";
}
...
if(indexPositions.size()==0){
isOne = "Yes";
}
else if(indexPositions.size()!=0){
Collections.sort(indexPositions);
isOne = "No,"+indexPositions.get(0)+"";
}
return isOne;
}
Sometimes you may initialize the variable with a default value too, even if in this case is not needed :
String isOne = "No";
In also in your code there is an "error", the indexPositions.size may only be 0 or more, so you may want to use else instead of else if, and complete the graph. In this case eclipse won't tell you to add a return statement anymore, even if you use the return inside the condition block.
if(indexPositions.size()==0) {
return "Yes";
}
else {
Collections.sort(indexPositions);
return "No,"+indexPositions.get(0)+"";
}
I usually do this by declaring a boolean at the start of the function and set it to false. If for whatever reason the function says that variable is gonna be true. I set the declared variable to true instead of returning true. At the end of the function i return that declared variable.
It then has its default return and if the variable was set to true, it returns true.

how to know if a string is inside an array on Android?

Hi everybody im programming an application in Android and I don`t know what to do to get this that I am trying. I now that it is very simple but please help me!
Lets say that I have an array:
String coco[] = { "hi", "everybody", "superman", "batman" };
And also I have a:
String heroe = "superman";
Now I need to make a loop, method or whatever, that takes "heroe" and search if that value ("superman") its inside the array and then so if that value exist TRUE and if don`t exist FALSE.
Thank you guys.
The most comfortable way is to convert the array to a list and search then.
It is clean, short and expressive.
boolean isThere = Arrays.asList(yourArray).contains("needle");
for(int i=0;i<coco.length;i++)
{
if(coco[i].equals(heroe))
return true;
}
Here is a simple solution. It would be easier to use an ArrayList that can use .contains ()method.
for(int i = 0; i < coco.length; i++)
{
if(coco[i].equals(heroe))
{
// a match!
return true;
}
}
// no match
return false;
Simply iterate over the values in the array and compare them to the value you're looking for
public boolean arraySearch(String[] strArray, String key) {
for (String s : strArray) {
if (s.equals(key)) {
return true;
}
}
return false;
}
You can use this by calling arraySearch(coco, heroe); in your code.
Alternatively you could use the Arrays class and use:
boolean keyPresent = Arrays.asList(coco).contains(heroe);
you could do some thing like this:
for (String testcoco : coco)
{
if (testcoco.contains("superman"))
{
return true;
}
}
return false;
You can do like this.
Just take a variable which you want to search and iterate the array and use equals method.
String heroe = "superman";
boolean flag = false;
for(int index = 0; index < coco.length; index++)
{
Strin value = coco[index];
if(heroe.equals(value))
{
flag = true;
}
}
if(flag) {
//Exist
}
else {
//Not Exist
}
public boolean checkPresence(String desired)
for(String s:coco){
if(s.equals(desired)){
return true
}
}
return false;

Categories