Bug 754

Summary: Scanner return java.util.NoSuchElementException when a function finish execution
Product: coworking space management system Reporter: yongjiawu5-c
Component: systemAssignee: yongjiawu5-c
Status: RESOLVED FIXED    
Severity: normal CC: yongjiawu5-c
Priority: ---    
Version: release1   
Hardware: PC   
OS: Windows   

Description yongjiawu5-c 2022-12-05 06:16:01 HKT
Error message:
Exception in thread "main" java.util.NoSuchElementException: No line found
	at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
	at System.Main.main(Main.java:14)

Steps to reproduce:
1. Run main
2. input "Reg"
3. input username and password and confirm
4. error occurs

IDE: Eclipse IDE 2021-06 (4.20.0)

Java Version: JDK 17

Related Code:
1. Main class main method
2. CmdRegister class getParamList method
Comment 1 yongjiawu5-c 2022-12-05 06:17:40 HKT
Receive the error. Working on it.
Comment 2 yongjiawu5-c 2022-12-05 06:20:13 HKT
Solved the issue.

Reason:
no need to close the scanner inside a called function. Otherwise the scanner in main function will be eliminated.

Solution:
remove the scanner closure command in CmdRegister class

Modified code:
package System;

import java.util.Scanner;

public class CmdRegister implements Command {
	public CmdRegister() {}
	
	public String[] getParamList() {
		Scanner in = new Scanner(System.in);
		String[] paramList = new String[2];
		System.out.print("Username:");
		paramList[0] = in.nextLine();
		System.out.print("Password:");
		paramList[1] = in.nextLine();
		return paramList; 
	}
	
	public void execute(Role role, String[] paramList) {
		if(paramList!=null&&role.canRegister()) {
			ManagementPortal managementPortal = ManagementPortal.getInstance();
			managementPortal.register(paramList);
		}
		else if(paramList==null) {}
		else {
			System.out.print("Logged in user cannot register.\n");
		}	
	}
}