7

スキャナーにループで入力を取得させようとしています。ユーザーが終了したい場合は、このループを終了できます。私はそれを行うためにさまざまな方法を試しましたが、常にいくつかの問題があります。これはコードです:

private void inputEntries() {
    Scanner sc = new Scanner(System.in);
    System.out.println("Continue?[Y/N]");
    while (sc.hasNext() && (sc.nextLine().equalsIgnoreCase("y"))) {//change here
        System.out.println("Enter first name");
        String name = sc.nextLine();
        System.out.println("Enter surname");
        String surname = sc.nextLine();
        System.out.println("Enter number");
        int number = sc.nextInt();
        Student student = new Student(name, surname, number);
        students.add(student);
        try {
            addToFile(student);
        } catch (Exception ex) {
            Logger.getLogger(TextReader.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Continue?[Y/N]");
    }
}

上記のコードの問題は、私が試したさまざまな方法でも発生しますが、ユーザーがYScanner入力すると、最初の名前の入力がスキップされ、姓にジャンプすることです。ユーザーがNと入力すると、ループは正しく停止します。Scannerこれが発生する理由と、クラスを使用して克服する方法を誰かが説明できますか?

ps: のようなwhile(sc.nextLine().equals("Y"))ことをすると、ループの最初の実行後、ユーザーからの入力を取得する前にループが終了します。

4

4 に答える 4

9

これは、Scanner#nextメソッドを使用しているためです。そのメソッドのドキュメントを見ると、次に読み取られたトークンが返されます。

そのため、メソッドを使用してユーザー入力を読み取ると、最後にnextが読み取られません。その後、ループ内でnewline読み取られます。したがって、知らないうちに a が含まれています。nextLine()whilefirstNamenewline

nextLine()そのため、 while ではなくを使用する必要がありますnext()

nextIntメソッドの場合も同様です。また、改行も読みません。したがって、を使用して、それを使用readreadLine変換できます。入力値を に変換できない場合にスローされる可能性があります。したがって、それに応じて処理する必要があります。intInteger.parseIntNumberFormatExceptionint

以下のコードを試すことができます: -

Scanner sc = new Scanner(System.in);
System.out.println("Continue?[Y/N]");
while (sc.hasNext() && (sc.nextLine().equalsIgnoreCase("y"))) {//change here
    System.out.println("Enter first name");
    String name = sc.nextLine();
    System.out.println("Enter surname");
    String surname = sc.nextLine();
    System.out.println("Enter number");
    int number = 0;
    try {
        number = Integer.parseInt(sc.nextLine());
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }
    System.out.println("Continue?[Y/N]");
}

ただし、渡すことができない値をInteger.parseInt入力すると、例外が発生し、その入力はスキップされることに注意してください。その場合は、whileループを使用して処理する必要があります。

または、その例外処理をしたくない場合: -

次のように、残りを消費するempty sc.nextLine()afterを追加できます。sc.nextInt()newline

    // Left over part of your while loop

    String surname = sc.nextLine();
    System.out.println("Enter number");
    int number = sc.nextInt();
    sc.nextLine(); // To consume the left over newline;
    System.out.println("Continue?[Y/N]");
于 2012-10-21T16:57:36.273 に答える
4
  • YまたはNが小文字になること、およびその逆equalsIgnoreCase(..)を防ぐために使用します。
  • 次のブレークまで読み取る間、次のスペースまでしか読み取らないため、目的を達成するためにsc.next()むしろ使用しないでください。sc.nextLine()next()nextLine()\n
  • nextInt()read all data asStringを使用してから convertを使用しないでください。これは、次の\nまで読み取らないためnextInt()です。next()

次のようにしてみてください。

Scanner sc = new Scanner(System.in);
System.out.println("Continue?[Y/N]");

while (sc.hasNext() && (sc.nextLine().equalsIgnoreCase("y"))) {//change here

    System.out.println("Enter first name");
    String name = sc.nextLine();

    System.out.println("Enter surname");
    String surname = sc.nextLine();

    System.out.println("Enter number");

    int number=0;

    try {
    number = Integer.parseInt(sc.nextLine());//read int as string using nextLine() and parse
    }catch(NumberFormatException nfe) {
        nfe.printStackTrace();
    }

    System.out.println("Continue?[Y/N]");
}
于 2012-10-21T16:53:55.277 に答える
1
public void display() {
    int i, j;
    for (i = 1; i <= 5; i++) {
        for (j = i; j < 5; j++) {
            System.out.print(" ");
        }
        for (j = 1; j < (2 * i); j++) {
            System.out.print(i % 2);
        }
        for (j = 1; j < ((5 * 2) - (i * 2)); j++) {
            System.out.print(" ");
        }
        for (j = 1; j < (2 * i); j++) {
            System.out.print(j);
        }
        System.out.println();
    }
    for (i = 4; i >= 1; i--) {
        for (j = i; j < 5; j++) {
            System.out.print(" ");
        }
        for (j = 1; j <= i; j++) {
            System.out.print(j);
        }
        for (j = i - 1; j >= 1; j--) {
            System.out.print(j);
        }
        for (j = 1; j < ((5 * 2) - (i * 2)); j++) {
            System.out.print(" ");
        }
        for (j = 1; j < (2 * i); j++) {
            System.out.print(j);
        }
        System.out.println();
    }
}
于 2015-09-27T12:38:32.193 に答える