Bug 754 - Scanner return java.util.NoSuchElementException when a function finish execution
Summary: Scanner return java.util.NoSuchElementException when a function finish execution
Status: RESOLVED FIXED
Alias: None
Product: coworking space management system
Classification: Unclassified
Component: system (show other bugs)
Version: release1
Hardware: PC Windows
: --- normal
Assignee: yongjiawu5-c
URL:
Depends on:
Blocks:
 
Reported: 2022-12-05 06:16 HKT by yongjiawu5-c
Modified: 2022-12-05 06:23 HKT (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
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");
		}	
	}
}