Making a decision using array of the character type

Viewed 42

So what I'm trying to do is to get a result by reading if certain characters are contained within the arrays. First the Strings are converted to arrays of the character type so that each letter becomes a value and not just the whole word becoming one value. then the if statement should check if the arrays contain the specified letters and give the result.

public class string {
    public static void main(String[] args){
        System.out.println  ("  hello world");

        String name = "y";
        String surname = "o";

        long id = 45;

        char[] cname = new char[name.length()];

        char[] csurname = new char[surname.length()];



        if (cname.contains("q") && csurname.contains("d")) {
            System.out.println("aa" + id + "zz");

        }else{
            System.out.println("gg" + id + "gg");
        }
    }
}

1 Answers

new char[name.length()]; creates an array of that length, all with \u0000 (null character). You would need to initialize all positions to the needed values like cname[0] = 'y';


You shouldn't need to do that since to get an array from a String, you'd use .toCharArray().

However, arrays do not have .contains method, only lists do...


To test if a substring is in another string, you don't need arrays, just call .contains() on the string.

String name = "y";
String surname = "o";
int id = 45;
if (name.contains("q") && surname.contains("d")) {
    System.out.printf("aa%dzz%n", id);
} else {
    System.out.printf("gg%dgg%n", id);
}
Related