0

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");
        }
    }
}

3
  • 5
    You know that "q" + "p" + " a" + "z" turns this into the String "qpaz", right? You probably want to do separate boolean tests for each letter, no? Or use Regex. Commented Sep 7, 2022 at 20:20
  • 3
    BTW new String(cname) is creating a string full of \u0000 since the arrays are full of that character (initial value) Commented Sep 7, 2022 at 20:41
  • 1
    Every time you edit the question, it invalidates the comments you've been given so far. Commented Sep 7, 2022 at 21:14

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.