原文: https://beginnersbook.com/2014/07/java-program-to-get-input-from-user/

在本教程中,我们将看到如何接受来自用户的输入。我们使用Scanner类来获取输入。在下面的例子中,我们得到输入字符串,整数和浮点数。为此,我们使用以下方法:

1)public String nextLine():用于获取String输入

2)public int nextInt():用于整数输入

3)public float nextFloat():用于float输入

例:

  1. import java.util.Scanner;
  2. class GetInputData
  3. {
  4. public static void main(String args[])
  5. {
  6. int num;
  7. float fnum;
  8. String str;
  9. Scanner in = new Scanner(System.in);
  10. //Get input String
  11. System.out.println("Enter a string: ");
  12. str = in.nextLine();
  13. System.out.println("Input String is: "+str);
  14. //Get input Integer
  15. System.out.println("Enter an integer: ");
  16. num = in.nextInt();
  17. System.out.println("Input Integer is: "+num);
  18. //Get input float number
  19. System.out.println("Enter a float number: ");
  20. fnum = in.nextFloat();
  21. System.out.println("Input Float number is: "+fnum);
  22. }
  23. }

输出:

  1. Enter a string:
  2. Chaitanya
  3. Input String is: Chaitanya
  4. Enter an integer:
  5. 27
  6. Input Integer is: 27
  7. Enter a float number:
  8. 12.56
  9. Input Float number is: 12.56

参考:

扫描仪 Javadoc