簡體   English   中英

使用掃描儀獲取用戶輸入

[英]Getting User input with Scanner

我想讓掃描儀在循環中接收輸入。 一旦用戶想要完成,他就可以退出這個循環。 我嘗試了很多不同的方法,但總有一些問題。 這是代碼:

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]");
    }
}

上面代碼的問題,也發生在我嘗試的不同方法上,當用戶鍵入Y時Scanner將跳過第一個名字輸入,並跳轉到姓氏。 如果用戶鍵入N,則循環正確停止。 有人可以解釋這種情況發生的原因,以及如何克服使用Scanner類?

ps:做一些像while(sc.nextLine().equals("Y"))這樣的事情會導致循環在第一次運行循環后從用戶輸入之前終止。

這是因為您正在使用Scanner#next方法。 如果查看該方法的文檔,它將返回下一個標記讀取。

因此,當您使用next方法讀取用戶輸入時,它不會在最后讀取newline 然后由while循環中的nextLine()讀取。 因此,你的firstName包含一個你不知道的newline

所以,你應該在你的while而不是next()使用nextLine() next()

nextInt方法類似。 它也不會讀取換行符。 因此,您可以使用readLine read並使用Integer.parseInt將其轉換為int 如果輸入值無法轉換為int ,則可能拋出NumberFormatException 所以你需要相應地處理它。

您可以嘗試以下代碼: -

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()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]");
  • 使用equalsIgnoreCase(..)來防止YN的情況為小寫,反之亦然。
  • 不要使用sc.nextLine() sc.next()而不是sc.nextLine()來實現你想要的,因為next()只讀取下一個空格,而nextLine()讀取到下一個\\n中斷。
  • 不要使用nextInt()將所有數據讀取為String然后轉換,因為nextInt()就像next()因此不會讀取到下一個\\ n

試試這樣:

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]");
}

你可以用

String abc = "abc";
String answer = "null";
while (abc.equals("abc")
{
if (answer.equals("n")
{
break;
}
while (answer.equals("y"))
{
//Put your other code here
System.out.print("Continue? [y/n]")
answer = input.nextLine();
if (answer.equals("n")
{
break;
}
}
}

這應該在輸入時停止程序

"n"

您還必須導入並創建如下掃描器:

//This is how you import the Scanner
import java.util.Scanner;
//This is how you create the Scanner
Scanner input = new Scanner(System.in);
/**
*The name
*/
"input"
/**
*is used because of
*/
input.nextLine
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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM