Java 程序获取用户输入
在这篇文章中,我们将了解如何在 Java 中从用户获取输入。这是通过使用扫描器对象实现的。 Scanner.nextInt() 方法 用于获取输入。java.util.Scanner.nextInt() 方法将输入的下一个标记扫描为整数。此方法的调用形式为nextInt(),其行为与调用 nextInt(radix) 相同,其中 radix 是此扫描器的默认基数。
问题陈述
编写一个 Java 程序来获取用户输入。下面是相同的演示 -
输入
Hello, I am John!
输出
The input string is: Hello, I am John!
获取用户输入的方法
以下是获取用户输入的不同方法 -
使用 Scanner 类
以下是使用 Scanner 类在 Java 中从用户获取输入的步骤 -
- 首先从 java.util 包 中导入 Scanner 类。
- 实例化Scanner 对象以从控制台读取输入。
- 通知用户并提示输入。
- 使用scanner.nextLine()捕获用户输入的整行文本并将其存储在名为 value 的变量中。
- 打印消息,后跟存储在 value 中的用户输入。
示例
在这里,用户根据提示输入输入。您可以在 我们的 编码 练习工具 中实时尝试此示例。
import java.util.Scanner;
public class PrintString{
public static void main(String[] args){
String value;
Scanner scanner = new Scanner(System.in);
System.out.println("A reader object has been defined ");
System.out.print("Enter a string: ");
value = scanner.nextLine();
System.out.println("The nextLine method is used to read the string value ");
System.out.println("The string is: ");
System.out.println(value);
}
}t
输出
A reader object has been defined Enter a string: Good Morning! The nextLine method is used to read the string value The string is: Good Morning!
使用 InputStreamReader 和 BufferReader
以下是使用 InputStreamReader 和 BufferReader 在 Java 中从用户获取输入的步骤 -
- 从 java.io 包 中导入所有类
- 创建InputStreamReader 对象以从控制台读取数据。
- 通过打印创建消息通知用户 InputStreamReader 对象已成功创建。
- 将 InputStreamReader 包装在 BufferedReader 中以进行高效读取。
- 通过打印构造函数消息告诉用户BufferedReader 对象现在已准备就绪。
- 提示用户输入。
- Integer.parseInt(in.readLine())读取输入作为字符串,将其转换为整数,并将其存储在number变量中。
示例
在这里,用户使用InputStreamReader 对象根据提示输入输入。您可以在 我们的 编码 练习工具 中实时尝试此示例。
import java.io.*;
public class readNum{
public static void main(String args[]) throws IOException{
InputStreamReader read=new InputStreamReader(System.in);
System.out.println("An object of InputStreamReader class is created");
BufferedReader in=new BufferedReader(read);
System.out.println("A constructor of the BufferedReader class is created");
System.out.println("Enter a number: ");
int number=Integer.parseInt(in.readLine());
}
}
输出
An object of InputStreamReader class is created A constructor of the BufferedReader class is created Enter a number: 34
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP