Java 键盘输入的常用方法,Scanner的常用方法,输出时的要点
!!!在java编译器中,要使用输入时需要先import java.util.Scanner;或者简单点import java.util.*;
定义Scanner变量
Scanner sc = new Scanner(System.in);/*sc 是变量;System.in 代表从键盘获得输入;*/
定义完sc后,并不能直接使用sc!!!还需要将sc转成其他类型才能使用。
外围代码
mport java.util.Scanner;//或者import java.util.*;
public class Output
{
public static void main(String[] args)
{......................}
}
!!!
!!!
!!!
以下演示有个点需要大家注意一下:
每次输入,我们都只使用且**只使用一次(划重点)**其中的任一一个方法获得输入
!!!
!!!
!!!
以下所有演示代码均为public static void main(String[] args){…}内的代码。
Scanner的常用方法有:
- next()获得一个无空格的连续的输入(第一个空格前的输入),返回类型总是为String
System.out.println("Input1:");
Scanner sc = new Scanner(System.in);/*sc 是变量,System.in 代表从键盘获得输入*/
System.out.println("Input2:");
System.out.println("Output:"+sc.next());
注意不管Input1在sc前还是Input2在sc后都先于Output在窗体输出
- nextLine()获得一整行无转行的输入(输入可包括空格),返回类型为String
System.out.println("Input1:");
Scanner sc = new Scanner(System.in);/*sc 是变量,System.in 代表从键盘获得输入*/
System.out.println("Output:"+sc.nextLine());
- nextInt()获得无空格的连续的整数(第一个空格前的整数,可包括负号),返回类型为int
简单来说相当于将next()的返回类型String转成Int类型
即Integer.parseInt(sc.next());和sc.nextInt();两种方法得到的效果是一样的。
System.out.println("Input1:");
Scanner sc = new Scanner(System.in);/*sc 是变量,System.in 代表从键盘获得输入*/
System.out.println("Output:"+sc.nextInt());
- nextDouble()类比 nextInt()方法,返回类型为double
- nextFloat()类比 nextInt()方法,返回类型为float
说完Scanner的常用方法后,最有意思的部分来了!!!!
**上面提到 **
之前的得到的输出都不是Scanner的全部内容,倒不如说是输出的Scanner.xxxxx()得到的内容。
我们来试试多次且用不同方法输出Scanner
System.out.println("Input1:");
Scanner sc = new Scanner(System.in);
System.out.println("Output:\n"+sc.next());
System.out.println(sc.nextInt());
System.out.println(sc.nextDouble());
我们会发现每个方法都是按顺序各取所需
由上一代码得到的结果,我们也可以知道:当使用nextLine()来获取内容时,得到的是sc还未输出的剩下的内容(在其他方法前使用时获取的就是全部)
*
*
*
*
*
*
*
哎呀,好晚了都,去睡了。