nextLine()和next()的区别和使用方法
来源:互联网 发布:java按键监听器 编辑:程序博客网 时间:2024/05/19 14:20
在实现字符窗口的输入时,我个人更喜欢选择使用扫描器Scanner,它操作起来比较简单。在写作业的过程中,我发现用Scanner实现字符串的输入有两种方法,一种是next(),一种nextLine(),但是这两种方法究竟有什么区别呢?我查了一些资料总结了一下,希望对大家有所帮助~
鉴于以上两种方法的只要区别,同学们一定要注意next()方法和nextLine(0方法的连用,下面举个例子来说明:
import java.util.Scanner;public class NextTest { public static void main(String[] args) { // TODO Auto-generated method stub String s1,s2; Scanner sc=new Scanner(System.in); System.out.print("请输入第一个字符串:"); s1=sc.nextLine(); System.out.print("请输入第二个字符串:"); s2=sc.next(); System.out.println("输入的字符串是:"+s1+" "+s2); }}
运行结果:
请输入第一个字符串:home
请输入第二个字符串:work
输入的字符串是:home
但如果把程序改一下,
运行结果是:
请输入第一个字符串:home
请输入第二个字符串:输入的字符串是:home
可以看到,nextLine()自动读取了被next()去掉的Enter作为他的结束符,所以没办法给s2从键盘输入值。经过验证,我发现其他的next的方法,如double nextDouble()
import java.util.Scanner;
public class NextTest {
}
运行结果是:
请输入第一个字符串:home
请输入第二个字符串:work
输入的字符串是:home
- nextLine()和next()的区别和使用方法
- nextLine()和next()的区别和使用方法
- next()和nextLine()的区别
- next()和nextLine()的区别
- next()和nextline()的区别
- next()和nextLine()的区别
- next()和nextLine()的区别
- next和nextLine的区别
- next和nextLine的区别
- next()和nextLine()的区别
- next()和nextLine()的区别
- nextLine和next的区别
- next()和nextLine()的区别
- next()和nextLine()区别
- next()和nextline()区别
- Scanner的next()和nextLine()的区别
- java中next()和nextLine()的区别
- sc.next() 和 nextLine 的区别
- OpenMP实现生产者消费者模型
- Hdu 4111 Alice and Bob(博弈+记忆化搜索)
- Codeforces Round #261 (Div. 2) C. Pashmak and Buses
- leetcode - Candy
- USB端口数据分析
- nextLine()和next()的区别和使用方法
- 怎样在Word中插入代码并保持样式不变
- 获取JAVA文件路径
- HDU 3371 Connect the Cities
- struts与spring整合的原理
- Java实现快速排序
- 大型网站架构
- 编程实现识别内网中进行ARP欺骗的主机
- hdu 1428 漫步校园 (最短路+记忆化搜索)