关于scanner的简单问题。

llm0528 2008-10-28 05:11:53
问题简单,请看注释。
import java.util.*;

public class Test2 {

private int a;
private long b;
private float c;
private double d;
private String e;

private String scanner;
Test2(String s){
scanner = s;
}

public static void main(String[] args){
Test2 test2 = new Test2("myString\n10\n20\n30.123\n" +
"40.123\nMyString");
Scanner sc = new Scanner(test2.scanner);
test2.e = sc.nextLine();//System.out.println(test2.e + "");
test2.a = sc.nextInt();
test2.b = sc.nextLong();
test2.c = sc.nextFloat();
test2.d = sc.nextDouble();
test2.e = sc.next(); //如果这换成 sc.nextLine()的话将什么都没有 这是为什么呢?
System.out.println("a = " + test2.a + ", b = " + test2.b +
", c = " + test2.c + ", d = " + test2.d + ", e = "
+ test2.e + ".");
}
}
...全文
101 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
ZangXT 2008-10-28
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 llm0528 的回复:]
很抱歉的告诉大家,在MyString后面加\n是无效的。其实我发出来的是修改过的代码,我试验用写的比较乱,当时我在MyString\nmyString是这样的。但是也无效~~
[/Quote]
告诉你再nextLinue一次了。
llm0528 2008-10-28
  • 打赏
  • 举报
回复
很抱歉的告诉大家,在MyString后面加\n是无效的。其实我发出来的是修改过的代码,我试验用写的比较乱,当时我在MyString\nmyString是这样的。但是也无效~~
qusic 2008-10-28
  • 打赏
  • 举报
回复
楼上说的没错,nextLine是找换行符的
你的字符串最后没有换行符,所以就找不到
在字符串最好加个“\n”就可以使用nextLine()了
shuaiAWP 2008-10-28
  • 打赏
  • 举报
回复
学习
个人看法nextLine()方法读取的是一个文本行
文本行的结束标志是\n
最后一个没有\n所以方法将找不到文本行
renmms 2008-10-28
  • 打赏
  • 举报
回复
每次nextXXX方法都是读取数据XXX\n,最后一个没有\n,所以说问题出在\n上
ZangXT 2008-10-28
  • 打赏
  • 举报
回复
是不是\n的影响
再执行一次nextLine()就ok了。
不很了解正则表达式,不深入分析了。
newsonglin 2008-10-28
  • 打赏
  • 举报
回复
确实不明白,难道是Java中的bug,期望达人解释一下。
justinavril 2008-10-28
  • 打赏
  • 举报
回复
第一个问题不明白;
第二个问题:This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.你在MyString后面加上\n看有没有输出?

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧