Java Scanner 类读取字符串

时间:2023-02-25
本文介绍了Java Scanner 类读取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到以下代码:

int nnames;
String names[];

System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
names = new String[nnames];

for (int i = 0; i < names.length; i++){
  System.out.print("Type a name: ");
  names[i] = in.nextLine();
}

该代码的输出如下:

How many names are you going to save:3 
Type a name: Type a name: John Doe
Type a name: John Lennon

注意它是如何跳过名字条目的?它跳过它,直接进入第二个名称条目.我已经尝试寻找导致这种情况的原因,但我似乎无法确定它.我希望有一个人可以帮助我.谢谢

Notice how it skipped the first name entry?? It skipped it and went straight for the second name entry. I have tried looking what causes this but I don't seem to be able to nail it. I hope someone can help me. Thanks

推荐答案

报错原因是nextInt只拉取整数,没有拉取换行符.如果你在你的 for 循环之前添加一个 in.nextLine(),它会吃掉新的空行并允许你输入 3 个名字.

The reason for the error is that the nextInt only pulls the integer, not the newline. If you add a in.nextLine() before your for loop, it will eat the empty new line and allow you to enter 3 names.

int nnames;
String names[];

System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();

names = new String[nnames];
in.nextLine();
for (int i = 0; i < names.length; i++){
        System.out.print("Type a name: ");
        names[i] = in.nextLine();
}

或者只是读取该行并将值解析为整数.

or just read the line and parse the value as an Integer.

int nnames;
String names[];

System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = Integer.parseInt(in.nextLine().trim());

names = new String[nnames];
for (int i = 0; i < names.length; i++){
        System.out.print("Type a name: ");
        names[i] = in.nextLine();
}

这篇关于Java Scanner 类读取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:从列表中删除重复元素 下一篇:Java +从int数组中计算重复项而不使用任何集合或

相关文章

最新文章