Java: Talking about input and output

Input and output in Java

Input:
In the Java language, to input data from the keyboard, using the Scanner class should be the most common. Scanner is a new class of JDK1.5, we can use this class to create an object.
as follows:

Scanner input = new Scanner(System.in);

After that, the input object calls the following methods to read various data types entered by the user on the command line:

input
调用
nextLine()/next()
nextInt()
nextDouble()
nextByte()
nextShort()
nextFloat
nextLong()
nextBlooean()
next().char(0)
输入字符串
输入intl类型
输入double类型
输入byte类型
输入short类型
输入long类型
输入字符类型
输入float类型

Output:
System,out.print(); and System,out.println(); in Java can output string values ​​and expression values. The difference is that the former will not wrap while the latter will wrap. It should be noted that when using them to output string constants, there cannot be a carriage return, otherwise it cannot be compiled. If the length of the output character constants is too long, you can use a concatenation to connect them:

System,out.print("你好!
很高兴认识你!");//错误写法
System,out.println("你好!
很高兴认识你!");//错误写法
System,out.print("你好!"+
"很高兴认识你!");//正确写法
System,out.println("你好!"+
"很高兴认识你!");//正确写法

In addition, JDK1.5 also added a new data output method similar to the printf function in C language. The format of this method is as follows:

System.out.printf("格式控制部分",表达式1,表达式2,表达式3,.....,表达式n);

Finally, let us end today's sharing with an example!

import java.util.Scanner;

public class test {
    
    
//该程序循环输入数据直到用户输入一个非数字字符循环结束
	public static void main(String[] args) {
    
    
		Scanner input = new Scanner(System.in);
		double sum = 0;
		int m = 0;
		while(input.hasNextDouble()) {
    
    
			double x = input.nextDouble();
			m += 1;
			sum += x;
			}
		System.out.printf("%d 个数的和为: %f\n",m,sum);
		System.out.printf("%d 个数的平均值是 %f\n", m,sum);
	}
	}

Guess you like

Origin blog.csdn.net/qq_43825377/article/details/106066846