hmg11 2020-03-22 22:02 采纳率: 0%
浏览 249

在for循环里使用nextline会报错Exception in thread 使用next就不会,是什么原因,求大佬

package demo2;
import java.util.ArrayList;
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
ArrayListas=new ArrayList<>();
for(int i=0;i<3;i++) {
String name=in.nextLine();
Student s=new Student(name);
while(true) {
String course=in.next();
if(course.equals("#")) {break;}
int mark=in.nextInt();
s.addCourse(new Course(course,mark));
}
as.add(s);
}
for(Student st:as) {
System.out.println(st);
}
}
}

  • 写回答

1条回答 默认 最新

  • 轻点 别打脸 2020-03-23 11:08
    关注
    public String nextLine() {
        if (hasNextPattern == linePattern())
            return getCachedResult();
        clearCaches();
    
        String result = findWithinHorizon(linePattern, 0);
        if (result == null)
            throw new NoSuchElementException("No line found");
        MatchResult mr = this.match();
        String lineSep = mr.group(1);
        if (lineSep != null)
            result = result.substring(0, result.length() - lineSep.length());
        if (result == null)
            throw new NoSuchElementException();
        else
            return result;
    }
    
    
        看源码,nextLine() 首先就进行了下一个模块的判断,hasNextPattern为空,自然报错
    
    评论

报告相同问题?