简体   繁体   中英

Beginner - Java Programming While Loop

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:

在此处输入图片说明

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; .

because your setName function is wrong

it should be:

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

you put newName = name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM