Java Scanner学习记录

1. Java.util.Scanner可以用来从键盘获取输入

Scanner.next()  只能读取字符,遇到任何的符合都不会输出

Scanner.nextLine()  会完全按照用户输入的string输出

Example1 for Scanner.next():

package com.mengdd.junit;
import java.util.*;

public class ScanDemo {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);//get data from keyboard
//get date with nextline
System.out.println("get date with next: ");
if (scan.hasNext()){
String str = scan.next();
System.out.print(str);
}
}
}

run this class and input: I am entering a line to test
after running, the output would be:
get date with next:
I
All strings after I will not be outputed


Example 2 for Scanner.nextLine():
package com.mengdd.junit;

import java.util.Scanner;

/**
* Created by Sandy.Liu on 2017/6/22.
*/
public class ScanDemo1 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("please enter a string");
if(scan.hasNextLine()){
String str = scan.nextLine();
System.out.print(str);
}
}
}

run this class and the result will be:

please enter a string
hellow i am entering a line to test
hellow i am entering a line to test
Process finished with exit code 0

 

So nextLine() will get every single character the user inputs even the punctuation

转载于:https://www.cnblogs.com/xiaohai2003ly/p/7065340.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值