Java uses the java.util.Scanner class to read input from the console: read data from the console by creating a Scanner object and passing it into System.in (standard input stream):
// 从控制台读取一个字符串和一个整数的例子
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // 创建Scanner对象
System.out.print("Input your name: "); // 打印提示
String name = scanner.nextLine(); // 读取一行输入并获取字符串
System.out.print("Input your age: "); // 打印提示
int age = scanner.nextInt(); // 读取一行输入并获取整数
System.out.printf("Hi, %s, you are %d\n", name, age); // 格式化输出
}
}
operation result:
This type of input method is often used in written examination questions. Here is a simple example: design a program to input the scores of the last exam and the scores of this exam, and then output the percentage of score improvement, retaining two decimal places (for example, 10.55% ).
public class scanner {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your last test score:");
float lastScore = scanner.nextFloat();
if (lastScore == 0){
System.out.println("The last test score cannot be 0");
return;
}
System.out.print("Enter your score for this test:");
float thisScore = scanner.nextFloat();
float improvementPercentage = (thisScore - lastScore) / lastScore;
System.out.printf("The percentage of improvement in grades = %.2f%%",improvementPercentage * 100);
}
}
operation result: