为了账号安全,请及时绑定邮箱和手机立即绑定

在字符串数组中保存几个名字

在字符串数组中保存几个名字

BIG阳 2023-03-17 15:55:22
问题是编写一个名为 Seyyed 的类包含一个名为 seyyed 的方法。我应该在 main 方法中将一些人的名字保存在一个字符串数组中,并计算有多少名字以“Seyyed”开头。我写了下面的代码。但是输出是意想不到的。问题出在第 10 行,第一次打印了两次“Enter a name :”这句话。import java.util.Scanner;public class Seyyed {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        System.out.print("Enter the number of names :");        int n = in.nextInt();        String[] names = new String[n];        for (int i = 0; i < names.length; i++) {            System.out.println("Enter a name : ");            names[i] = in.nextLine();        }        int s = seyyed(names);        System.out.println("There are " + s + " Seyyed");        in.close();    }    static int seyyed(String[] x) {        int i = 0;        for (String s : x)            if (s.startsWith("Seyyed"))                i++;        return i;    }}例如,当我输入 3 以添加 3 个名称时,程序会重复“输入名称:”这句话 2 次,输出如下所示:Enter the number of names :3Enter a name : Enter a name : Seyyed SaberEnter a name : Ahmad AliThere are 1 Seyyed我可以输入 2 个名称,而我希望输入 3 个名称。
查看完整描述

4 回答

?
婷婷同学_

TA贡献1844条经验 获得超8个赞

当您按下回车键时出现问题,这是一个换行符 \n 字符。nextInt() 仅使用整数,但它会跳过换行符 \n。要解决这个问题,您可能需要在读取 int 后添加一个额外的 input.nextLine(),它可以消耗 \n。

在刚刚in.nextInt();添加in.nextLine();以消耗输入中的额外 \n 之后。这应该工作。

原答案: https://stackoverflow.com/a/14452649/7621786


查看完整回答
反对 回复 2023-03-17
?
绝地无双

TA贡献1946条经验 获得超4个赞

当您输入数字时,您还按下了 Enter 键,这将执行一个“\n”输入值,该值由您的第一个 nextLine() 方法捕获。为防止这种情况,您应该在代码中插入 nextLine() 以在读取 int 值后使用“\n”字符。


Scanner in = new Scanner(System.in);

        System.out.print("Enter the number of names :");

        int n = in.nextInt();

        in.nextLine();

        String[] names = new String[n];

同一问题的好答案:https ://stackoverflow.com/a/7056782/4983264


查看完整回答
反对 回复 2023-03-17
?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

nextInt() 将消耗整数的所有字符,但不会触及行尾字符。所以当你在循环中第一次调用 nextLine() 时,它会读取前一个 scanInt() 留下的 eol,所以基本上读取一个空字符串。要修复此问题,请在循环之前使用 nextLine() 来清除扫描仪或对字符串和整数使用不同的扫描仪。



查看完整回答
反对 回复 2023-03-17
?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

试试这个:


public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    System.out.print("Enter the number of names :");

    int n = in.nextInt();

    in.nextLine();

    String[] names = new String[n];

    for (int i = 0; i < names.length; i++) {

        System.out.println("Enter a name : ");

        names[i] = in.nextLine();

    }

    int s = seyyed(names);

    System.out.println("There are " + s + " Seyyed");

    in.close();

}


static int seyyed(String[] x) {

    int i = 0;

    for (String s : x)

        if (s.startsWith("Seyyed"))

            i++;

    return i;

}


查看完整回答
反对 回复 2023-03-17
  • 4 回答
  • 0 关注
  • 158 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号