0

I posted this question up earlier and it was pretty much a lazy post as I didn't provide the code I had and as a result got negged pretty badly. Thought I'd create a new one of these ....

I have an array dogArray which takes ( name, secondname, dogname )

I want to be able to change the dogname:

here's my attempt :

public void changeName(Entry [] dogArray) {
    Scanner rp = new Scanner(System.in);
String namgeChange = rp.next();  {
    for (int i = 0; i < dogArray.length; i++){
        for (int j = 0; j < dogArray[i].length; j++){
            if (dogArray[i][j] == name){
                dogArray[i][j] = nameChange; 
            }
        }
    }
}

For a start it doesn't like the fact I've used ' name ' although it is defined in the dogArray. I was hoping this would read input so that users are able to change 'name' to whatever they input. This will change the value of name in the array.

Do you guys think I'm getting anywhere with my method or is it a pretty stupid way of doing it?

1
  • 2
    Entry is not an array so you cannot index it. Why would you use a nested loop do your dogs have dogs or something? The logic for your if is the opposite of what it should be. dogArray[i] cannot store Strings as you attempt to do in the if, entries only. Commented Apr 16, 2014 at 19:53

1 Answer 1

2

Only one loop is necessary, also move your call to next.

public void changeName(Entry [] dogArray) {
    Scanner rp = new Scanner(System.in);
    for (int i = 0; i < dogArray.length; i++){
        String nameChange = rp.next();  {
        if(!dogArray[i].name.equals(nameChange)){
            dogArray[i].name = nameChange; 
        }
    }
}

You might want to make this function static as well and use accessors and mutators to change and get the name. Might want to tell the user what you want them to type as well. Also there is no point in testing if the name changed, if it changed then set it, if it didnt change then set it (it doesnt hurt). Just get rid of if and keep the code inside.

Sign up to request clarification or add additional context in comments.

3 Comments

What's the point of changing dog's name from nameChange to nameChange?
Doing it with if you would test then set or just test. Doing it without if would set or set. Which potentially saves one operation.
Oh I missed a not (!) as it was not in the original code. Good catch @JBNizet

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.