首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >结果不正确的数据录入问题?

结果不正确的数据录入问题?
EN

Stack Overflow用户
提问于 2019-05-16 20:37:28
回答 2查看 44关注 0票数 0

看到代码了。当我启动程序时,它不让我将scanner类输入插入到开关中,为什么?

代码语言:javascript
运行
复制
Scanner in = new Scanner(System.in);

System.out.println("select:");
int select = in.nextInt();

switch (select) {
case 1:
System.out.println("first name:");
String n = in.nextLine();
System.out.println("surname:");
String s = in.nextLine();

System.out.println(n + s);
break;
}

输出:

选择:1名字:姓氏:

EN

回答 2

Stack Overflow用户

发布于 2019-05-16 21:41:17

由于nextInt方法中留有一个换行符,因此忽略了nextLine方法。有两种方法可以解决这个问题。

解决方案1:

代码语言:javascript
运行
复制
Scanner in = new Scanner(System.in);
System.out.println("select:");
int select = in.nextInt();

in.nextLine();

解决方案2:

代码语言:javascript
运行
复制
Scanner in = new Scanner(System.in);
System.out.println("select:");
int select = Integer.parseInt(in.nextLine());
票数 1
EN

Stack Overflow用户

发布于 2019-05-16 21:39:50

BufferedReaderInputStreamReader替换Scanner可以修复它,请尝试:

代码语言:javascript
运行
复制
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

System.out.println("select:");
int select = Integer.parseInt(input.readLine());

switch (select) {
    case 1:
        System.out.println("first name:");
        String n = Integer.parseInt(input.readLine());
        System.out.println("surname:");
        String s = Integer.parseInt(input.readLine());

        System.out.println(n + s);
    break;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56168746

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档