在本教程中,我们将看到如何接受来自用户的输入。我们使用Scanner
类来获取输入。在下面的例子中,我们得到输入字符串,整数和浮点数。为此,我们使用以下方法:
1)public String nextLine()
:用于获取String
输入
2)public int nextInt()
:用于整数输入
3)public float nextFloat()
:用于float
输入
例:
import java.util.Scanner;
class GetInputData
{
public static void main(String args[])
{
int num;
float fnum;
String str;
Scanner in = new Scanner(System.in);
//Get input String
System.out.println("Enter a string: ");
str = in.nextLine();
System.out.println("Input String is: "+str);
//Get input Integer
System.out.println("Enter an integer: ");
num = in.nextInt();
System.out.println("Input Integer is: "+num);
//Get input float number
System.out.println("Enter a float number: ");
fnum = in.nextFloat();
System.out.println("Input Float number is: "+fnum);
}
}
输出:
Enter a string:
Chaitanya
Input String is: Chaitanya
Enter an integer:
27
Input Integer is: 27
Enter a float number:
12.56
Input Float number is: 12.56