簡體   English   中英

如何在Java中以空格分隔的用戶輸入

[英]How can I take user input separated by space in Java

System.out.print("Enter an integer width and height between 2 and 25: ");
String[] str = sc.next().split(" ");
System.out.print(str.length);

我想采用由空格分隔的用戶輸入,但它只采用第一個輸入。

在此處輸入圖片說明

您應該使用sc.nextLine()代替 sc.next ()

根據 javadoc, sc.next() Finds and returns the next complete token from this scanner.

sc.next()將首先返回“ token ”(在您的情況下為 10,因為您的輸入由 10 到 20 之間的“空格”標記)。

因此,您的代碼應如下所示,符合您的期望:

    Scanner sc = new Scanner(System.in);
    System.out.print("Enter an integer width and height between 2 and 25: ");
    String[] str = sc.nextLine().split(" ");
    System.out.print(str.length);
    sc.close();

暫無
暫無

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

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