采取多个输入并存储它们

时间:2017-12-10 16:30:05

标签: java arrays input

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

1 个答案:

答案 0 :(得分:0)

使用String f = s.next();代替String f = s.nextLine();