0

This code keeps on looping every time I enter something. How to fix it?

public void inputPlayer()
{
    Scanner input = new Scanner(System.in);
    while(name.length() < 1)
    {
        System.out.println("Name: ");
        this.setName(input.nextLine());
        //name = input.nextLine();

        if(name.length() < 1)
            System.err.println("Must have one or more characters");
    }
}

Heres' a screenshot of the whole thing:

enter image description here

7
  • 1
    What actually you want ? Commented Aug 20, 2015 at 8:00
  • Unless this.setName changes name (don't know, you haven't given the code), nothing changes the guard condition, so it will never break. Commented Aug 20, 2015 at 8:01
  • 1
    while(name.length() < 1) where is name declared? Commented Aug 20, 2015 at 8:02
  • 1
    @DanyalSandeelo have a look at the image he posted, theres everything. Commented Aug 20, 2015 at 8:04
  • 1
    Don't post code as images, post text. Commented Aug 20, 2015 at 8:10

2 Answers 2

5

The problem is visible in the screenshot, and is with your setName() method, which is currently:

public void setName(String newName) {
    newName = name;
}

The assignment is the wrong way around, so you never update your name field. It should be name = newName;.

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

3 Comments

@JoshuadV I'd have expected some angry IDE squiggles or the like, but in a simple class like that it stood out well enough regardless.
Beat me to it by a few seconds.
Hey edd thanks for your help! really appreciate it! :D
1

because your setName function is wrong

it should be:

    public void setName(String newName) {
        name = newName;
    }

you put newName = name;

1 Comment

Hello hughzi! thanks for the help man! :D you guys are really fast at replying.

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.