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

问题是编写一个名为 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 :3

Enter a name : 

Enter a name : 

Seyyed Saber

Enter a name : 

Ahmad Ali

There are 1 Seyyed

我可以输入 2 个名称,而我希望输入 3 个名称。


BIG阳
浏览 159回答 4
4回答

婷婷同学_

当您按下回车键时出现问题,这是一个换行符 \n 字符。nextInt() 仅使用整数,但它会跳过换行符 \n。要解决这个问题,您可能需要在读取 int 后添加一个额外的 input.nextLine(),它可以消耗 \n。在刚刚in.nextInt();添加in.nextLine();以消耗输入中的额外 \n 之后。这应该工作。原答案:&nbsp;https://stackoverflow.com/a/14452649/7621786

绝地无双

当您输入数字时,您还按下了 Enter 键,这将执行一个“\n”输入值,该值由您的第一个 nextLine() 方法捕获。为防止这种情况,您应该在代码中插入 nextLine() 以在读取 int 值后使用“\n”字符。Scanner in = new Scanner(System.in);&nbsp; &nbsp; &nbsp; &nbsp; System.out.print("Enter the number of names :");&nbsp; &nbsp; &nbsp; &nbsp; int n = in.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; in.nextLine();&nbsp; &nbsp; &nbsp; &nbsp; String[] names = new String[n];同一问题的好答案:https ://stackoverflow.com/a/7056782/4983264

幕布斯6054654

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

慕桂英3389331

试试这个:public static void main(String[] args) {&nbsp; &nbsp; Scanner in = new Scanner(System.in);&nbsp; &nbsp; System.out.print("Enter the number of names :");&nbsp; &nbsp; int n = in.nextInt();&nbsp; &nbsp; in.nextLine();&nbsp; &nbsp; String[] names = new String[n];&nbsp; &nbsp; for (int i = 0; i < names.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Enter a name : ");&nbsp; &nbsp; &nbsp; &nbsp; names[i] = in.nextLine();&nbsp; &nbsp; }&nbsp; &nbsp; int s = seyyed(names);&nbsp; &nbsp; System.out.println("There are " + s + " Seyyed");&nbsp; &nbsp; in.close();}static int seyyed(String[] x) {&nbsp; &nbsp; int i = 0;&nbsp; &nbsp; for (String s : x)&nbsp; &nbsp; &nbsp; &nbsp; if (s.startsWith("Seyyed"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; return i;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java