日期:2014-05-20  浏览次数:20713 次

关于scanner的简单问题。
问题简单,请看注释。
Java code
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 + ".");
    }
}



------解决方案--------------------
第一个问题不明白;
第二个问题: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看有没有输出?
------解决方案--------------------
确实不明白,难道是Java中的bug,期望达人解释一下。
------解决方案--------------------
是不是\n的影响
再执行一次nextLine()就ok了。
不很了解正则表达式,不深入分析了。
------解决方案--------------------
每次nextXXX方法都是读取数据XXX\n,最后一个没有\n,所以说问题出在\n上
------解决方案--------------------
学习
个人看法nextLine()方法读取的是一个文本行
文本行的结束标志是\n
最后一个没有\n所以方法将找不到文本行
------解决方案--------------------
楼上说的没错,nextLine是找换行符的
你的字符串最后没有换行符,所以就找不到
在字符串最好加个“\n”就可以使用nextLine()了
------解决方案--------------------
探讨
很抱歉的告诉大家,在MyString后面加\n是无效的。其实我发出来的是修改过的代码,我试验用写的比较乱,当时我在MyString\nmyString是这样的。但是也无效~~