簡體   English   中英

如何在 Java 的 for 循環中獲取不同數據類型的多個用戶輸入?

[英]How do you take multiple user inputs of different data types within a for loop in Java?

我試圖提示用戶輸入一個字符串,該字符串將存儲在一個字符串數組中,然后是一個輸入的 int,該 int 將被放入一個 int 數組中。

我遇到了打印第一行的問題,但沒有提示用戶輸入字符串。 然后立即打印第二個打印語句,用戶只能輸入一個整數。

到目前為止,我有:

    int i, n = 10;
    String[] sentence = new String[1000];
    int[] numbers = new int[1000];



    for(i = 0; i < n; i++)
        {
        System.out.println("Enter String" + (i + 1) + ":");
        sentence[i] = scan.nextLine();

        System.out.printf("Enter int " + (i + 1) + ":");
        numbers[i] = scan.nextInt();
        }

作為輸出,我得到:

Enter String 1:
Enter int 1:

在這里你可以輸入一個int,它被存儲到int數組中。 但是您不能為字符串數組輸入字符串。

請幫忙。

像這樣放置scan.nextLine():

for(i = 0; i < n; i++){
    System.out.println("Enter String" + (i + 1) + ":");
    sentence[i] = scan.nextLine();

    System.out.printf("Enter int " + (i + 1) + ":");
    numbers[i] = scan.nextInt();
    scan.nextLine();

}

此問題是由於nextInt()方法引起的。

這里發生的是, nextInt()方法使用用戶輸入的整數,但不使用在按Enter鍵時創建的用戶輸入末尾的換行符。

因此,當您在輸入整數后按Enter鍵時,對nextLine()下一次調用將使用nextLine() ,而nextInt()方法在循環的最后一次迭代中不會使用該換行符。 這就是為什么它在循環的下一個迭代中跳過String的輸入並且不等待用戶輸入String

您可以在nextInt()調用之后調用nextLine()來消耗nextLine()

for(i = 0; i < n; i++)
{
    System.out.println("Enter String" + (i + 1) + ":");
    sentence[i] = scan.nextLine();

    System.out.printf("Enter int " + (i + 1) + ":");
    numbers[i] = scan.nextInt();
    scan.nextLine();             // <------ this call will consume the new line character
}

使用 sc.next(); 而不是 sc.nextLine(); 如果無法在第一次迭代中輸入字符串值。

Scanner sc = new Scanner(System.in);

for(i = 0; i < n; i++);
    System.out.println("Enter String" + (i + 1) + ":");
    sentence[i] = sc.next();

    System.out.printf("Enter int " + (i + 1) + ":");
    numbers[i] = sc.nextInt();
    sc.nextLine();
}

暫無
暫無

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

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