next()和nextLine()都不有助于使用空格存储名称 [英] Both next() and nextLine() not helping to store name with spacing

查看:35
本文介绍了next()和nextLine()都不有助于使用空格存储名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在使用扫描仪来记录用户输入(即字符串)并将其打印出来.如果用户输入是单个名称(例如Alan),则可以正常工作.如果我输入一个带有空格的名称,例如Alan Smith,它将返回一个错误,提示InputMisMatchException.

I am currently using a Scanner to record the user input which is a String and print it out. If the user input is a single name such as Alan, it works fine. If I enter a name with spacing such as Alan Smith, it returns an error saying InputMisMatchException.

我在这里阅读了类似的案例,他们建议使用nextLine()代替next().这是有道理的,但这对我也不起作用.当我使用nextLine()时,它将立即跳过输入名称的步骤,并返回到循环的起点,要求我再次输入选择.请提出建议,我该如何纠正.谢谢.

I read around similar cases here and they advised to use nextLine() instead of next(). It made sense but that doesn't work for me either. When I use a nextLine(), it immediately skips the step where I enter the name and goes back to the starting of the loop asking me to input choice again. Please advice how I can correct this. Thank you.

import java.io.IOException;
import java.util.Scanner;

public class ScannerTest {
    static String name;
    static Scanner in = new Scanner(System.in);
    static int choice;

    public static void main(String[] args) {      
        while(choice != 5){
            System.out.print("\nEnter Choice :> ");
            choice = in.nextInt();

            if(choice == 1){
                try{
                    printName();
                }
                catch(IOException e){
                    System.out.println("IO Exception");
                }
            }
        } 
    }  
    private static void printName()throws IOException{
        System.out.print("\nEnter name :> ");
        name = in.next();
        //name = in.nextLine(); 
        if (name != null){
            System.out.println(name);
        }
    }  
}  

推荐答案

尝试以下操作:在choice = in.nextInt();之后添加name = in.nextLine();.

Try this instead: add name = in.nextLine(); after choice = in.nextInt();.

然后尝试将name = in.next();替换为name = in.nextLine();

说明:扫描程序调用nextInt()后,它将获得第一个值,并将字符串的其余部分留给\n.然后,我们使用nextLine()消耗字符串的其余部分.

Explanation: After the scanner calls nextInt() it gets the first value and leaves the rest of the string to the \n. We then consume the rest of the string with nextLine().

第二个nextLine()然后用于获取您的字符串参数.

The second nextLine() is then used to get your string parameters.

这篇关于next()和nextLine()都不有助于使用空格存储名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆