关于nextLine()和next()的使用
来源:互联网 发布:北大青鸟怎么编程 编辑:程序博客网 时间:2024/05/16 06:32
Java Scanner not working, difference between next() and nextLine()
When I was a newbie programmer, I used to be frustrated a lot every time I used the Scanner class. At the time, it seemed like it behaved erratically and no matter how much debugging I did, it was always wrong.
The mistake I was making was that I failed to realize that whenever I used a .next call, like nextInt or nextDouble, the Scanner would stay on the same line. If then, I wanted to scan a new input that was on a different line, the Scanner will appear to skip it. What happens is that the Scanner is actually scanning the invisible newline character!
So, whenever you want to Scan numbers with a .next() call, make sure you add an empty .nextLine() at the end so that the Scanner moves to the correct position.
Ex:
package com.tarena.corejava;
import java.util.Scanner;
public class MyScanner {
public static void main(String[] args) {
}
Sample run
Please enter the grade: 76 Please enter name: Name: , grade: 76.0
Sample run
Please enter the grade: 100 Please enter name: Rommel Name: Rommel, grade: 100.0
Beautiful!
解决方案一:
next() 在 nextLine 之前使用时,next 扫描空格或换行之前的字符,并没有读入"\n" , 而nextLine 则要从"\n" 开始读入,所以得不到数据、
正确方法:
- int
n = cin.nextInt(); - while(str = cin.nextLine().equles(""))
- {
- }
- 关于nextLine()和next()的使用
- 关于nextLine()和next()的使用
- 关于nextLine()和next()的使用
- 关于nextLine()和next()的使用,区别
- 关于nextLine()和next()的使用
- 关于nextLine()和next()的使用
- 关于Scanner对象的nextLine()和next()的使用
- next() 和 nextLine() 的 区别
- next()和nextLine()的区别
- next()和nextLine()的区别
- next()和nextline()的区别
- next()和nextLine()的区别
- next()和nextLine()的区别
- next和nextLine的区别
- next和nextLine的区别
- next()和nextLine()的区别
- next()和nextLine()的区别
- nextLine和next的区别
- LeetCode 011 Container With Most Water
- 字典
- POJ 2887Big String(块状链表)
- 【Android游戏开发十六】Android Gesture之【触摸屏手势识别】操作!利用触摸屏手势实现一个简单切换图片的功能!
- 整形子类(int subtypes)
- 关于nextLine()和next()的使用
- WEB 前端学习收获
- 微信扫码关注后实现自动分组
- [leetcode 257] Binary Tree Paths
- 数据结构【一】数组实现固定容量字符串栈
- Round2 - Probability
- 20151209 Linux系统日常管理 (第三部分计划任务crontab;anacron)
- 【Android游戏开发十七】让玩家自定义手势玩转Android游戏!—Android Gesture之【输入法手势技术】
- UNIX网络编程笔记(7):回射程序的UDP版本