java1:从控制台读取输入

来源:互联网 发布:软件行业会计核算 编辑:程序博客网 时间:2024/05/21 06:34

Java uses System.out to refer to the standard 

output device and System.in to the standard input device. By default the output device is the display monitor, and the input  device is the keyboard。

 To perform console output, you simply use the println method to display a

primitive value or a string to the console. Console input is not directly supported in Java, but
you can use the Scanner class to create an object to read input from System.in, as follows:
Scanner input = new Scanner(System.in);
The syntax new Scanner(System.in) creates an object of the Scanner type. The syntax
Scanner input declares that input is a variable whose type is Scanner. The whole line
Scanner input = new Scanner(System.in) creates a Scanner object and assigns its ref-
erence to the variable input. An object may invoke its methods. To invoke a method on an
object is to ask the object to perform a task. 

java使用System.out 来表示标准的输出设备,用System.in来表示标准的输入设备。默认情况下,输出设备是显示器,输入设备是键盘(在后面我们会看到也可以从文件中输入)。我们直接使用println来完成控制台输出。像我们输出可以直接使用System.out.println("hello,world!"),但是我们不可以直接使用System.in来从键盘输入,我们需要借助Scanner类来读入System.in的输入。 使用如下:Scanner input = new Scanner(System.in);同时Scanner 提供一系列的方法来读取不同类型的输入

Scanner 对象提供的方法有:

1 nextByte():byte    读取一个byte 类型整数

2 nextShort(): short   读取一个short 类型整数

3 nextInt(): int  读取一个int 类型整数

4 nextLong(): long  读取一个long 类型整数

5 nextFloat() : float 读取一个float 类型浮点数

6 nextDouble(): double 读取一个double 类型浮点数

7 next():String  读取一个字符串,该字符在一个空白符之前结束(也就是说,不读入空白符)

8 nextLine():String 读取一行文本(会将回车键读入)

下面以从键盘输入半径,然后计算圆的面积(注:因为自己因为学习到后面的一些内容,所以在前边的一些例子会改动一些用到后面的一些,例如会使用Math.PI来表示或者用final double等)

import java.util.Scanner;public class ComputeArea{public static void main(String[] args){final double PI =3.14;  //或者使用Math类的Math.PIScanner input = new Scanner(System.in);System.out.print("input the radius:");double r=input.nextDouble(); double area=r*r*PI;System.out.println("when radius="+r+",the area="+area);}}



0 0
原创粉丝点击