首页 > 解决方案 > 为什么我的字符串变量在第二次分配给它之后是空的?

问题描述

我正在为学校做一个项目,我正试图让它在你可以为自己设置一个名字的地方,同时通过计算机提出的一系列问题。我希望用户能够在分配名称后立即更改他们的名称,如果他们不喜欢他们放下的内容或输入错误的内容。现在程序第一次正确地分配了用户想要的名称,但是当它通过循环返回以将其更改为其他名称时,字符串保留为空白。 控制台输出 '''

    import java.util.*;

    public class JavaInputProdject 
     {
        public static void main(String args[])
          {
            int i=0;
            boolean boo = false;
            int likeab = 0;
            byte age;
            boolean Old=false;
            boolean aAge=true;
            String user="User";
            String un = user + "> ";
            Scanner bob = new Scanner(System.in);
    
    System.out.print("Bob> Hey User, My name is BOB.... what is your name?\n"+un);
    
    do
        {
            user = bob.nextLine();
            System.out.println("Bob> This is the Username you want? \""+ user +"\"(true/false)");
            System.out.print(un);
             
            
            if(bob.nextBoolean()==true)
                {
                    boo = true;
                    un = user + "> ";
                }
            
            else
                {
                        if(i>=3)
                            {
                                System.out.println("Bob> I realize it is kind of hard to pick a name but could you hurry up?");
                            }
                    System.out.print("Bob> Please type in a new Username\n"+un);
                    bob.next();
                    i++;
                }
            
        } while(boo==false);
     }
    }

'''

标签: javastringjava.util.scanneruser-input

解决方案


当您想根据错误标志获得正确的用户名时,您不会为用户初始化一个值。你应该写这样的东西bob.nextLine

 System.out.print("Bob> Please type in a new Username\n"+un);
 user = bob.nextLine();
 i++;

推荐阅读