Java 程序获取用户输入
javaobject oriented programmingprogramming更新于 2024/4/12 2:20:17
在本文中,我们将了解如何在 Java 中获取用户输入。这是使用扫描仪对象实现的。Scanner.nextInt() 方法用于获取输入。
java.util.Scanner.nextInt() 方法将输入的下一个标记扫描为 int。调用此方法的形式 nextInt() 的行为与调用 nextInt(radix) 完全相同,其中 radix 是此扫描仪的默认基数。
下面是相同的演示 −
输入
假设我们的输入是 −
你好,我是约翰!
输出
期望输出为 −
输入字符串为:Hello, I am John!
算法
步骤 1- 开始 步骤 2- 声明字符串:值 步骤 3- 提示用户输入字符串 步骤 4- 读取值 步骤 5- 显示值 步骤 6- 停止
示例 1
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);
}
}
输出
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!
示例 2
此处,用户根据提示使用 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
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

