在这里,我们将解释如何编写 Java 程序以从用户读取不同类型的输入并显示它们。
在 Java 中,通过使用 Java Scanner 类的 nextLine() 方法从用户读取整数。因此,首先我们必须通过将 System.in 作为参数来创建 Scanner 类的对象。我们还需要导入 java.util.Scanner。示例如下所示。
Scanner sc = new Scanner(System.in);
n= sc.nextInt();
在 Java 中,通过使用 Java Scanner 类的 nextLine() 方法从用户读取字符串。示例如下所示。
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
在 Java 中,通过使用 Java Scanner 类的 nextfloat() 方法从用户读取浮点数。示例如下所示。
Scanner sc = new Scanner(System.in);
f= sc.nextFloat();
在 Java 中,通过使用 Java Scanner 类的 nextdouble() 方法从用户读取双精度浮点数。示例如下所示。
Scanner sc = new Scanner(System.in);
d= sc.nextDouble();
步骤 1:声明具有 public 修饰符的类 UserInput。
步骤2:打开main()开始程序,Java程序执行从main()开始
步骤 3:声明变量 n 为整数,f 为浮点数,d 为双精度浮点数,str 为字符串。
步骤 4:创建 Scanner 类的对象 sc。
步骤 5:使用 sc.nextLine() 从用户读取字符串到变量 str。
步骤 6:使用 System.out.println() 显示字符串 str。
步骤 7:使用 sc.nextInt() 从用户读取整数到变量 n。
步骤 8:使用 System.out.println() 显示数字 n。
步骤 9:使用 sc.nextFloat() 从用户读取浮点数到变量 f。
步骤 10:使用 System.out.println() 显示浮点数 f。
步骤 7:使用 sc.nextDouble() 从用户读取双精度浮点数到变量 d。
步骤 8:使用 System.out.println() 显示双精度浮点数 d。
import java.util.Scanner;
public class UserInput{
public static void main(String args[]){
int n;
float f;
double d;
String str;
Scanner sc = new Scanner(System.in);
//String
System.out.println("Enter the string: ");
str = sc.nextLine();
System.out.println("The String is: "+str);
//Integer
System.out.println("Enter an integer number: ");
n= sc.nextInt();
System.out.println("The Integer number is : "+n);
//Float
System.out.println("Enter the float number: ");
f= sc.nextFloat();
System.out.println("The float number is: "+f);
//Double
System.out.println("Enter the double number: ");
d= sc.nextDouble();
System.out.println("The double number is: "+d);
}
}
Enter the string: STEM The String is: STEM Enter an integer number: 10 The Integer number is : 10 Enter the float number: 20.3 The float number is: 20.3 Enter the double number: 50.63245 The double number is: 50.63245