Scanner - Exception in thread "main" - java

I have written a quite basic login system in Java. Theoretically speaking, everything should work and function properly. However, when I run the program and enter the username and password, it outputs an exception.
Here's my code:
import java.util.*;
/**
* A basic login system
* #author Jamie <jamie#jamie.no>
*/
public class LoginSystem
{
public static boolean isValidated = false;
private static String userName = "";
private static String password = "";
public static void main(String[] args) {
runConsole();
}
public static void runConsole() {
Scanner console = new Scanner(System.in);
for (int i = 0; i < 3 && !isValidated; i++) {
System.out.println("You have entered the following username: ");
userName = console.nextLine();
System.out.println("You have entered the following password: ");
password = console.nextLine();
isValidated = AuthenticateUser(userName, password);
}
if (isValidated) {
System.out.println("Access Granted. User is authenticated.");
} else {
System.out.println("Unauthorized Access.");
}
}
/**
* User authentication constructor
* #param userName The username.
* #param password The password.
* #return true if user is validated.
*/
public static boolean AuthenticateUser(String userName, String password) {
return (userName.equalsIgnoreCase("User1") && password.equals("Pass1"));
}
}
Screenshot of the exception msg:

From the documentation:
public class NoSuchElementException extends RuntimeException Thrown
by the nextElement method of an Enumeration to indicate that there are
no more elements in the enumeration.
However, when I tried your code on Eclipse, it's running free of errors.
But when I tried it on Code Playground, it gave me the same error.
You have entered the following username:
You have entered the following password:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at LoginSystem.runConsole(LoginSystem.java:25)
at LoginSystem.main(LoginSystem.java:11)
It seems it's a bug in their system. Because you need to input the userName and password for three loops in advance in one go at the very beginning of the run.
I went around this by wrapping the scan with hasNextLinewhich Returns true if there is another line in the input of this scanner.
So, it becomes:
if(console.hasNextLine()){
userName = console.nextLine();
}
if(console.hasNextLine()){
password = console.nextLine();
}

Related

Trying to finish off a java code program

I am working on a java code for school and I have spent days on it and I just don't think that I'm heading in the right direction. Here is the info on the project:
For security-minded professionals, it is important that only the appropriate people gain access to data in a computer system. This is called authentication. Once users gain entry, it is also important that they only see data related to their role in a computer system. This is called authorization. For the zoo, you will develop an authentication system that manages both authentication and authorization. You have been given a credentials file that contains credential information for authorized users. You have also been given three files, one for each role: zookeeper, veterinarian, and admin. Each role file describes the data the particular role should be authorized to access. Create an authentication system that does all of the following:
 Asks the user for a username
 Asks the user for a password
 Converts the password using a message digest five (MD5) hash
It is not required that you write the MD5 from scratch. Use the code located in this document and follow the comments in it to perform this operation.

Checks the credentials against the valid credentials provided in the credentials file
Use the hashed passwords in the second column; the third column contains the actual passwords for testing and the fourth row contains the
role of each user.

Limits failed attempts to three before notifying the user and exiting the program

Gives authenticated users access to the correct role file after successful authentication
The system information stored in the role file should be displayed. For example, if a zookeeper’s credentials is successfully authenticated, then the contents from the zookeeper file will be displayed. If an admin’s credentials is successfully authenticated, then the contents from the admin file will be displayed.
 Allows a user to log out
 Stays on the credential screen until either a successful attempt has been made, three unsuccessful attempts have been made, or a user chooses to exit
Here are the five text files I was given:
admin.txt
Hello, System Admin!
As administrator, you have access to the zoo's main computer system.
This allows you to monitor users in the system and their roles.
credentials.txt
griffin.keyes 108de81c31bf9c622f76876b74e9285f "alphabet soup" zookeeper
rosario.dawson 3e34baa4ee2ff767af8c120a496742b5 "animal doctor" admin
bernie.gorilla a584efafa8f9ea7fe5cf18442f32b07b "secret password" veterinarian
donald.monkey 17b1b7d8a706696ed220bc414f729ad3 "M0nk3y business" zookeeper
jerome.grizzlybear 3adea92111e6307f8f2aae4721e77900 "grizzly1234" veterinarian
bruce.grizzlybear 0d107d09f5bbe40cade3de5c71e9e9b7 "letmein" admin
validateCredentials.txt
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package authentication;
import java.security.MessageDigest;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
/**
*
* #author JoeP
*/
public class ValidateCredentials {
private boolean isValid;
private String filePath;
private String credentialsFileName;
public ValidateCredentials() {
isValid = false;
//filePath = "C:\\Users\\joep\\Documents\\NetBeansProjects\\ Authentication\\";
filePath = "";
credentialsFileName = "credentials";
}
public boolean isCredentialsValid(String userName, String passWord) throws Exception {
String original = passWord;
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
System.out.println("");
System.out.println("original:" + original);
System.out.println("digested:" + sb.toString()); //sb.toString() is what you'll need to compare password strings
isValid = readDataFiles(userName, sb.toString());
return isValid;
}
public boolean readDataFiles(String userName, String passWord) throws IOException {
FileInputStream fileByteStream1 = null; // File input stream
FileInputStream fileByteStream2 = null; // File input stream
Scanner inFS1 = null; // Scanner object
Scanner inFS2 = null; // Scanner object
String textLine = null;
boolean foundCredentials = false;
// Try to open file
System.out.println("");
System.out.println("Opening file " + credentialsFileName + ".txt");
fileByteStream1 = new FileInputStream(filePath + "credentials.txt");
inFS1 = new Scanner(fileByteStream1);
System.out.println("");
System.out.println("Reading lines of text.");
while (inFS1.hasNextLine()) {
textLine = inFS1.nextLine();
System.out.println(textLine);
if (textLine.contains(userName) && textLine.contains(passWord)) {
foundCredentials = true;
break;
}
}
// Done with file, so try to close it
System.out.println("");
System.out.println("Closing file " + credentialsFileName + ".txt");
if (textLine != null) {
fileByteStream1.close(); // close() may throw IOException if fails
}
if (foundCredentials == true) {
// Try to open file
System.out.println("");
System.out.println("Opening file " + userName + ".txt");
fileByteStream2 = new FileInputStream(filePath + userName + ".txt");
inFS2 = new Scanner(fileByteStream2);
System.out.println("");
while (inFS2.hasNextLine()) {
textLine = inFS2.nextLine();
System.out.println(textLine);
}
// Done with file, so try to close it
System.out.println("");
System.out.println("Closing file " + userName + ".txt");
if (textLine != null) {
fileByteStream2.close(); // close() may throw IOException if fails
}
}
return foundCredentials;
}
}
veterinarian.txt
Hello, Veterinarian!
As veterinarian, you have access to all of the animals' health records. This allows you to view each animal's medical history, current treatments/illnesses (if any), and maintain a vaccination log.
zookeeper.txt
Hello, Zookeeper!
As zookeeper, you have access to all of the animals information and their daily monitoring logs. This allows you to track their feeding habits, habitat conditions, and general welfare.
Finally, this is the code that I have so far, but when I try to run it in Netbeans it just won't work.
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.List;
import java.util.Scanner;
public class Authentication {
public static void main(String args[]) {
try {
Scanner scan = null;
scan = new Scanner(new File("credentials.txt"));
String credentials[][] = new String[100][4];
int count = 0;
while (scan.hasNextLine()) {
//read name and hased pass
credentials[count][0] = scan.next();
credentials[count][1] = scan.next();
//get original pass from file
String l[] = scan.nextLine().split("\"[ ]+");
l[0] = l[0].trim();
l[0] = l[0].replace("\"", "");
credentials[count][2] = l[0];
credentials[count][3] = l[1].trim();
count++;
}
//ask for user input
Scanner scanio = new Scanner(System.in);
boolean RUN = true;
int tries = 0;
while (RUN) {
System.out.println("**WELCOME**");
System.out.println("1) Login");
System.out.println("2) Exit");
int ch = Integer.parseInt(scanio.nextLine().trim());
if (ch == 1) {
//increment number of attempts
tries++;
//ask for user and pass
System.out.print("Input username:");
String username = scanio.nextLine();
System.out.print("Input password:");
String password = scanio.nextLine();
//generate hash
MessageDigest md;
md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
byte[] digest = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
String hPassword = sb.toString();
boolean badUser = true;
for (int i = 0; i < count; i++) {
if (username.contentEquals(credentials[i][0])) {
if (hPassword.contentEquals(credentials[i][1])) {
//everything looks good. login
List<String> data = null;
//check type of user and print
switch (credentials[i][3]) {
case "zookeeper":
data = Files.readAllLines(Paths.get("zookeeper.txt"), Charset.defaultCharset());
break;
case "admin":
data = Files.readAllLines(Paths.get("admin.txt"), Charset.defaultCharset());
break;
case "veterinarian":
data = Files.readAllLines(Paths.get("veterinarian.txt"), Charset.defaultCharset());
break;
default:
break;
}
for (String s : data) {
System.out.println(s);
}
//reset tries
tries = 0;
//now what to do?
System.out.println("\n1) Logout.");
System.out.println("2) Exit.");
ch = Integer.parseInt(scanio.nextLine().trim());
if (ch == 2) {
RUN = false;
}
badUser = false;
break;
}
}
}
if (badUser) {
System.out.println("Invalid Username or password.");
}
} else {
RUN = false;
break;
}
//thief alert!!
if (tries == 3) {
RUN = false;
System.out.println("Too many invlaid attempts.");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
PLEASE HELP ME!!!
THANK YOU!!!
Youa re getting a FileNotFoundException. That is, Netbeans is not finding your credentials.txt file (which possibly is located in a different directory). Make sure your credentials.txt file is located in your Netbeans project directory, as follows:
1) Find your project directory by going to the "Netbeans "Projects" tab, right-clicking in your project folder and selecting "Properties". The "Project folder" will be shown on at the top of the new window displayed (i.e. "C:\Users\admin\Documents\NetBeansProjects\YourProjectName").
2) Place your credentials.txt file in that project directory.
3) Re-run your code.

Password Masking in Java with Scanner

I'm a high school student learning Java and I want to know how to change input text automatically into an asterisk in Scanner. This is for a simple log-in system I have made for a project. My code is
Scanner scan = new Scanner(System.in);
boolean correctLogin = false;
String username;
String password;
String enteredUsername;
String enteredPassword;
while(correctLogin != true){
System.out.println("Enter Username: ");
enteredUsername = scan.nextLine();
System.out.println("Enter Password: ");
enteredPassword = scan.nextLine();
if(enteredUsername.equals("username") && enteredPassword.equals("passw00rd")){
System.out.println("You have entered the correct login info");
correctLogin = true;
break;
}
else{
System.out.println("Your login info was incorrect, please try again");
}
}
System.out.println("You are now logged in, good job!");
I want it so that when I type the password, it will automatically change into an asterisk.
try with this for password read:
Console console = System.console();
if(console != null){
console.readPassword("Enter Password: ");
}
I also had the same issue with my console java application and
I also do not want to display password in my IDE for security reasons.
So, to find the bug I had to debug against the productive environment. Here is my solution that works for me in IntelliJ IDEA:
public static String getPassword() {
String password;
Console console = System.console();
if (console == null) {
password = getPasswordWithoutConsole("Enter password: ");
} else {
password = String.valueOf(console.readPassword("Enter password: "));
}
return password;
}
public static String getPasswordWithoutConsole(String prompt) {
final JPasswordField passwordField = new JPasswordField();
return JOptionPane.showConfirmDialog(
null,
passwordField,
prompt,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION ? new String(passwordField.getPassword()) : "";
}
I am not sure if i get your question correctly, but still I will try to explain of what I understood.
To ensure that you see *** on the user screen you need to have some kind of a User interface written in HTML. I think in this case you are running your code in eclipse and via some kind of a main method. If that is the case then as Vince mentioned there is no benefit of ** since the letters would appear in the console.
What I would recommend is look for something basic web application tutorial and you would have more idea on how it works then.
HTH

Make the console wait for correct input by user to close

I have a java console application which checks for password. If the password is correct then and only then the application window should close. Otherwise if it is incorrect password , the application window should not close until and unless the correct password is entered. I am not able to find any right java keywords which would close application window if the correct password is entered.
Use System.exit():
public static void main(String[] args) {
while(true) {
// get password
if(passwordCorrect) {
System.exit(0);
}
}
}
Try this code:
import java.util.*;
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
String input = null;
do{
input = scn.nextLine();
if(input == "password"){
system.exit(0);
}
}
}

Java does not append to the .DAT file

I am writing a basic program that has 3 menu options: Create User, Sign In, and Exit. The user can then choose one of these menu options.
If they choose Create User, they will be prompted to enter a User ID and password (which must follow patterns), and will then check against a .DAT file to ensure the User ID has not already been taken. After successful completion, the program will write the new User ID and password to the end of the .DAT file.
If they choose Sign In, they will be prompted to enter their User ID, followed by their Password, and the program will then read the .DAT file to validate they are on record.
Choosing exit will display a message, "You have signed out."
I am fairly new at java programming just as a forewarning.
Issues I am encountering with my code:
Choosing new user does not append to the .DAT file
Choosing Sign In - program does not seem to correctly check .DAT file because even-
though I am entering an existing account information it still gives my error "Invalid User ID."
import java.io.*;
import java.util.*;
/**
* This program will utilize a menu structure and validate input if the user doesn't choose
* a correct option. Writes a new ID and password to .dat file when user chooses to
* create new user from menu.
*
* #author CMS
* #Date 7/28/2014
*/
public class Passwordv2 {
static boolean answer = true;
static final String MENUANSW = "[1-3]{1}", USERID = "[A-Z,a-z]{6}-[0-9]{2}"; //, PASSWORD = "";
static String iMenuOption="", iID, recPassword, recUserID, password;
static Scanner scanner,scannerDat;
static PrintWriter pw;
public static void main(String[] args) {
init();
while (answer == true) {
menu();
if (iMenuOption.equals("1")) createUser();
else
if (iMenuOption.equals("2")) signIn();
else {answer = false;}
}
closing();
} // end of main
public static void init(){
//User input scanner
scanner = new Scanner(System.in);
//PrintWriter
try {
pw = new PrintWriter(new FileOutputStream (new File ("account.dat"),true) );
}
catch(FileNotFoundException ex) {
}
} // end of INIT
public static String menu(){
do {System.out.println("Please select from the following:");
System.out.println("1. Create a New User");
System.out.println("2. Sign in");
System.out.println("3. Exit");
iMenuOption = scanner.next();
answer = isValMenuOption(iMenuOption);
if (answer == false) { System.out.print("Incorrect Choice. ");}
} while (!answer);
return iMenuOption;
}
public static boolean isValMenuOption(String iMenuOption) {
return(iMenuOption.matches(MENUANSW));
}
public static void createUser() {
boolean validID = true, newID = true;
do {if (!validID) {System.out.println("User ID did not meet requirements.");}
if (!newID) {System.out.println("This User ID has been taken.");}
System.out.println("Please select a User Id (6 letters, followed by a dash (-), followed by 2 numbers).");
iID = scanner.next();
validID = isValidID(iID);
newID = isNewID(iID);}
while (validID==false || newID == false);
boolean valLength = true, valNum = true, valUpper = true, valLower = true;
do{ System.out.println("Please select a Password:");
System.out.println("(6-12 characters, one number, one upper case, one lower case, no white space or symbols).");
password = scanner.next();
valLength = isValLength(password);
valNum = valNum(password);
valUpper = valUpper(password);
valLower = valLower(password);}
while (!valLength || !valNum || !valUpper || !valLower);
pw.println(iID);
pw.println(password);
//menu();
}
public static boolean isValidID(String iID){
return(iID.matches(USERID));
}
public static boolean isNewID(String iID){
answer = true;
// Dat file scanner
try {
scannerDat = new Scanner(new File("account.dat"));
scannerDat.useDelimiter("\r\n");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("File error");
System.exit(1);
}
while (scannerDat.hasNext()) {
recUserID = scannerDat.next();
recPassword = scannerDat.next();
if (recUserID.equals(iID)) {
answer = false;
break;
}
}
return answer;
}
public static boolean isValLength(String password) {
if (password.length() <6 || password.length() > 12) System.out.println("Password did not meet length requirements. ");
return(password.length() >= 6 && password.length() <= 12);
}
public static boolean valNum(String password) {
if (password.matches(".*[0-9].*") == false) System.out.println("Password must contain at least one number. ");
return(password.matches(".*[0-9].*"));
}
public static boolean valUpper(String password){
if (password.matches(".*[A-Z].*") == false) System.out.println("Password must contain one upper case letter.");
return (password.matches(".*[A-Z].*"));
}
public static boolean valLower(String password){
if (password.matches(".*[a-z].*") == false) System.out.println("Password must contain one lower case letter.");
return (password.matches(".*[a-z].*"));
}
public static void signIn() {
boolean newID;
System.out.println("Enter User ID.");
iID = scanner.next();
System.out.println("Enter Password.");
password = scanner.next();
newID = isNewID(iID);
if (newID == false) {
if (password.equals(recPassword)) {System.out.println("Authenticated. You have signed in.");}
else {System.out.println("Invalid Password.");}
}
else {System.out.println("Invalid User ID.");}
}
public static void closing(){
System.out.println("You signed out.");
pw.close();
}
} // end of program
My .DAT file simply has
aabbcc-11
Onetwo3
aaabbb-22
Onetwo34
Change this line:
scannerDat.useDelimiter("\r\n");
to
scannerDat.useDelimiter("\n");
Works for me!
The first bad thing you are doing is that you have a PrintWriter (pw) and a Scanner (scannerDat) both accessing the same file and neither of them closing the access to the file, except right at the end, the pw is closed.
isNewId is the main culprit. Inside here you are better off using a FileReader instead of a Scanner. Declare the FileReader locally within the method and ensure that the file access is closed before exiting, this procedure.
Also within isNewId - don't call System.exit(); In a program this size it's OK, but anything bigger than this it is a cardinal sin and you should never just exit a program as ungracefully as this.
You need to flush your PrintWriter in order for it to do append to the file immediately. Otherwise it would just store it in the buffer to write it into the file eventually
Also, please check what user #simo.3792095 said about your code. You should not have several file streams opened at the same time. Either open/close your streams every time you do something with them, or read the whole data file on program start, then work with in-memory data, then save on exit. It is much easier to work with in-memory data, but if your program crashes all of the in-memory changes will be lost.
Thanks for all who replied. In the end, the problem ended up being that I had a "rough draft" java class, which I then copied and pasted the code of into a new java class under the same java project, which seemed to be giving me issues. Once I created a new java project and used the valid java class it worked fine. I also added the pw.flush(); method to my code so I was able to append to the file immediately instead of upon closing. Also removed the system.exit.

Hide input on command line

I know that command line interfaces like Git and others are able to hide input from a user (useful for passwords). Is there a way to programmtically do this in Java? I'm taking password input from a user and I would like their input to be "hidden" on that particular line (but not on all of them). Here's my code for it (though I doubt it would be helpful...)
try (Scanner input = new Scanner(System.in)) {
//I'm guessing it'd probably be some property you set on the scanner or System.in right here...
System.out.print("Please input the password for " + name + ": ");
password = input.nextLine();
}
Try java.io.Console.readPassword. You'll have to be running at least Java 6 though.
/**
* Reads a password or passphrase from the console with echoing disabled
*
* #throws IOError
* If an I/O error occurs.
*
* #return A character array containing the password or passphrase read
* from the console, not including any line-termination characters,
* or <tt>null</tt> if an end of stream has been reached.
*/
public char[] readPassword() {
return readPassword("");
}
Beware though, this doesn't work with the Eclipse console. You'll have to run the program from a true console/shell/terminal/prompt to be able to test it.
Yes can be done. This is called Command-Line Input Masking. You can implement this easily.
You can uses a separate thread to erase the echoed characters as they are being entered, and replaces them with asterisks. This is done using the EraserThread class shown below
import java.io.*;
class EraserThread implements Runnable {
private boolean stop;
/**
*#param The prompt displayed to the user
*/
public EraserThread(String prompt) {
System.out.print(prompt);
}
/**
* Begin masking...display asterisks (*)
*/
public void run () {
stop = true;
while (stop) {
System.out.print("\010*");
try {
Thread.currentThread().sleep(1);
} catch(InterruptedException ie) {
ie.printStackTrace();
}
}
}
/**
* Instruct the thread to stop masking
*/
public void stopMasking() {
this.stop = false;
}
}
With using this thread
public class PasswordField {
/**
*#param prompt The prompt to display to the user
*#return The password as entered by the user
*/
public static String readPassword (String prompt) {
EraserThread et = new EraserThread(prompt);
Thread mask = new Thread(et);
mask.start();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String password = "";
try {
password = in.readLine();
} catch (IOException ioe) {
ioe.printStackTrace();
}
// stop masking
et.stopMasking();
// return the password entered by the user
return password;
}
}
This Link discuss in details.
JLine 2 may be of interest. As well as character masking, it'll provide command-line completion, editing and history facilities. Consequently it's very useful for a CLI-based Java tool.
To mask your input:
String password = new jline.ConsoleReader().readLine(new Character('*'));
There is :
Console cons;
char[] passwd;
if ((cons = System.console()) != null &&
(passwd = cons.readPassword("[%s]", "Password:")) != null) {
...
java.util.Arrays.fill(passwd, ' ');
}
source
but I don't think this works with an IDE like Eclipse because the program is run as a background process rather than a top level process with a console window.
Another approach is to use the JPasswordField in swing with the accompanying actionPerformed method:
public void actionPerformed(ActionEvent e) {
...
char [] p = pwdField.getPassword();
}
source
Here is an example using console.readPassword(...); in an IDE. I use Netbeans. Note: In your IDE, Scanner will be used and it will show the password!. In the console, console.readPassword(..) will be used and it will not show the password!.
public static void main(String[] args) {
//The jar needs to be run from the terminal for console to work.
Scanner input = new Scanner(System.in);
Console console = System.console();
String username = "";
String password = "";
if (console == null)
{
System.out.print("Enter username: ");
username = input.nextLine();
System.out.print("Enter password: ");
password = input.nextLine();
}
else
{
username = console.readLine("Enter username: ");
password = new String(console.readPassword("Enter password: "));
}
//I use the scanner for all other input in the code!
//I do not know if there are any pitfalls associated with using the Scanner and console in this manner!
}
Note: I do not know if there are any pitfalls associated with using the Scanner and console in this manner!
The class Console has a method readPassword() that might solve your problem.

Categories

Resources