Java中的Scanner.nextLine问题

时间:2016-02-04 02:31:34

标签: java java.util.scanner system.in

在Java中,我尝试过

try (Scanner sc = new Scanner(System.in)) {
    while (sc.hasNextLine()) {
        System.out.print("Name: ");
        String name = sc.nextLine();
        System.out.println("Name is \"" + name + "\"");
    }
}

但在请求输入之前它不会输出Name:

控制台只显示一个空的控制台窗口,我可以在其中输入名称。

在询问姓名之前,如何确保输出Name:

修改

try (Scanner sc = new Scanner(System.in)) {
    System.out.print("Name: ");

    while (sc.hasNextLine()) {
        String name = sc.nextLine();
        System.out.println("Name is \"" + name + "\"");

        System.out.print("Age: ");
        int age = sc.nextInt();
        System.out.println("Age is " + age);

        System.out.print("Name: ");
    }

3 个答案:

答案 0 :(得分:0)

将你的println 放在之前的while循环中,然后在最后添加一个。

try (Scanner sc = new Scanner(System.in)) {
    System.out.print("Name: ");        
    while (sc.hasNextLine()) {

        String name = sc.nextLine();
        System.out.println("Name is \"" + name + "\"");
        System.out.print("Name: ");
    }
}

扫描仪在运行下一个代码之前等待它接收输入,因此只需将打印件放在扫描仪之前,然后放在while循环的末尾。

答案 1 :(得分:0)

你应该把=== Pre-bind state information === LOG: DisplayName = InnVue.BOA.RoomControl (Partial) WRN: Partial binding information was supplied for an assembly: WRN: Assembly Name: InnVue.BOA.RoomControl | Domain ID: 10 WRN: A partial bind occurs when only part of the assembly display name is provided. WRN: This might result in the binder loading an incorrect assembly. WRN: It is recommended to provide a fully specified textual identity for the assembly, WRN: that consists of the simple name, version, culture, and public key token. WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue. LOG: Appbase = file:///C:/Users/KHAN/Documents/GitHub/innvue/InnVue.InnDesk/InnVue.InnDesk/InnVue.InnDesk/ LOG: Initial PrivatePath = C:\Users\KHAN\Documents\GitHub\innvue\InnVue.InnDesk\InnVue.InnDesk\InnVue.InnDesk\bin Calling assembly : (Unknown). === LOG: This bind starts in default load context. LOG: Using application configuration file: C:\Users\KHAN\Documents\GitHub\innvue\InnVue.InnDesk\InnVue.InnDesk\InnVue.InnDesk\web.config LOG: Using host configuration file: LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config. LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind). LOG: Attempting download of new URL file:///C:/Users/KHAN/AppData/Local/Temp/Temporary ASP.NET Files/root/41f4bb6c/382c05ac/InnVue.BOA.RoomControl.DLL. LOG: Attempting download of new URL file:///C:/Users/KHAN/AppData/Local/Temp/Temporary ASP.NET Files/root/41f4bb6c/382c05ac/InnVue.BOA.RoomControl/InnVue.BOA.RoomControl.DLL. LOG: Attempting download of new URL file:///C:/Users/KHAN/Documents/GitHub/innvue/InnVue.InnDesk/InnVue.InnDesk/InnVue.InnDesk/bin/InnVue.BOA.RoomControl.DLL. ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated. 放在while循环之前,如下所示:

[BadImageFormatException: Could not load file or assembly 'InnVue.BOA.RoomControl' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +36
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +21
   System.Reflection.Assembly.Load(String assemblyString) +28
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: Could not load file or assembly 'InnVue.BOA.RoomControl' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +738
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +217
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
   System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +92
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +290
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +157
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +531

[HttpException (0x80004005): Could not load file or assembly 'InnVue.BOA.RoomControl' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9942412
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +90
   System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +456

如果您想了解此问题的原因,请查看此link1link2

答案 2 :(得分:0)

这可能是更好的设计,以避免重复的代码。 不必将循环结束条件限制为while语句;)

    try (Scanner sc = new Scanner(System.in)) {
        while (true) {
            System.out.print("Name: ");
            if (!sc.hasNextLine()) break;
            String name = sc.nextLine();
            System.out.println("Name is \"" + name + "\"");
        }
    }

修改: 由于sc.nextInt()没有吃换行符,因此您的修改无法正常使用,因此请sc.nextLine()之后放置sc.nextInt()