簡體   English   中英

接受多個輸入並將其存儲

[英]Taking multiple inputs and storing them

package assign;

import java.util.Scanner;

public class File {
public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    System.out.println("How many chef do we have?");
    int x = s.nextInt();
    String [] names = new String[x];
    if(x <= 0) { 
        do { 
        System.out.println("Please enter a valid number:");
        x = s.nextInt();
        }while (x <= 0); 
        }

    for (int m = 0; m <= x-1; m++) { 
        System.out.println("Enter the name of " + m + ":");
        String f = s.nextLine();
        names [m] = f;
    }
  }
}

因此,我的目的是盡可能多地從用戶那里獲取用戶的姓名。 但是我從這段代碼的輸出是這樣的:

  How many chef do we have?
  3
  Enter the name of 0:
  Enter the name of 1:
  John
  Enter the name of 2:
  Jack

當我更改String f = s.nextLine(); 行到int f = s.nextInt(); 問題按順序排列,我可以寫數字。 我應該怎么做才能像這樣:

   How many chef do we have?
   3
   Enter the name of 0:
   Bob
   Enter the name of 1:
   John
   Enter the name of 2:
   Jack

使用String f = s.next(); 而不是String f = s.nextLine();

暫無
暫無

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

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