exception in thread "main" java.util.nosuchelementexception code example

Example: exception in thread "main" java.util.nosuchelementexception

//broken:
public static void main(String[] args){
	String firstLine=readLine();
  	String secondLine=readLine();//will not work
}

public static String readLine(){
	Scanner scan=new Scanner(System.in);
	String line=scan.nextLine();//throws a NoSuchElementException the second time the method is called
	scan.close();//this also closes System.in
  	return line;
}
//working: reuse the Scanner:
public static void main(String[] args){
  	Scanner scan=new Scanner(System.in);
	String firstLine=readLine(scan);
  	String secondLine=readLine(scan);//will not work
 	scan.close();//this also closes System.in	
}

public static String readLine(Scanner scan){
	String line=scan.nextLine();//throws a NoSuchElementException the second time the method is called
  	return line;
}

Tags:

Java Example