Weird Behaviour with the java scanner utility [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
I'm not sure how dumb I am or if I am missing something quite simple; anyhow, I am trying to get a basic username and password input from the user using the scanner utility.
I have made sure scanner was initialised correctly (Scanner sc = new Scanner(System.in)
System.out.print("Username or Email: ");
String username = sc.nextLine();
System.out.print("\nPassword: ");
String password = sc.nextLine();
The issue I am having is when I run this part of the code (above), the output I get looks like this (below) where I start inputting into the password section. Its as though it is just skipping over the first call to the scanner.
Username or Email:
Password: (this is where my input goes)
My only guess is that the scanner is taking the second printing as its input but I am not sure so any help is greatly appreciated.
p.s I will leave the entire method at the bottom incase it helps.
Thanks.
public static void loginPage() throws SQLException{
int requestCounter = 0;
do {
System.out.print("Username or Email: ");
String username = sc.nextLine();
System.out.print("\nPassword: ");
String password = sc.nextLine();
boolean validLoginRequest = accountLoginCheck(username, password);
if (validLoginRequest) {
break;
} else {
requestCounter++;
}
} while (requestCounter < 3);
if (requestCounter == 3) {
System.out.println("Too many attempts");
return;
}
System.out.print("TO MAIN MENU");

Remove \n from System.out.print("\nPassword: ");
Username or Email: myemail
Password: pass

Related

Resource leaked in many places Java using Scanner

I've been spending the last 42 mnins trying to figure the error out on why it states
Resource leaked: 'myFirstname' and many other decleared variables
including myObj when its ran.
You only need one Scanner. That warning is because you never close the Scanner. Normally that is a valuable warning, but when the Scanner wraps System.in closing it will also close System.in so normally you don't close such a Scanner. However, you can do so before the program ends; and the easiest way is a try-with-Resources. Also, you compare the scanner myUsername with the String newUsername and close an if body with an unfortunately placed ;. Fixing all of that, it should look something like
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter your First Name");
String firstName = scan.nextLine();
System.out.println("Enter your Last Name");
String lastName = scan.nextLine();
System.out.println("Enter your Year of Employment");
String yearVar = scan.nextLine();
String newUsername = firstName.substring(0, 1) + lastName;
System.out.println("Username: " + newUsername);
String newPassword = firstName.substring(0, 3) + yearVar + lastName.substring(0, 3);
System.out.println("Password: " + newPassword);
System.out.println("Enter your Username");
String userName = scan.nextLine();
System.out.println("Enter your Password");
String passWord = scan.nextLine();
if (userName.equals(newUsername)) {
System.out.println("Would you like to change your password?");
}
}
You are creating a lot of Scanner object, and closing none of them. This cause the resources to be leaked. To close them and stop the leaks, add: myScanner.close() once you are finished with it.
Besides it could be better to use less scanner objects and reuse one in order to optimize your code.
EDIT: As pointed out by Elliott Frisch answer, closing a scanner wrapping System.in will close it as well, which is usually not wanted.

How To Mask a password input in java console

I'm building a login system in Java and I'm trying to mask the password input due to security measures but can't seem to find a way around it. This is what I'm Trying to do:
Username:
User1
Password:******
Here's my code to give you an idea
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner Input = new Scanner (System.in);
System.out.println("Username:");
String Username = Input.nextLine();
System.out.println("Password:");
String Password = Input.nextLine();
}
}
Try readPassword() method of java
It doesn't mask a * but it hide the input we type to console
cnsl = System.console();
char[] pwd = cnsl.readPassword("Password: ");
System.out.println("Password is: "+pwd);
like this.......
You can use Console.readPassword() from https://docs.oracle.com/javase/7/docs/api/java/io/Console.html

How to restart Java method after termination

I'm new to Java and thought I would make one of the classic Username and Password validation programs which I have successfully made with no obvious bugs, however I would like the program to essentially restart the input if the user enters the in-correct information. How would I go about restarting the program successfully each time the users enters wrong information?
Code below:
import java.util.Scanner;
public class UserPass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String user; //Creating user-name variable.
String pass; //Creating password variable.
System.out.println("Enter username here: "); //Message to tell user to input the user-name.
user = input.nextLine(); //Taking the users user-name input.
System.out.println("Enter the password here: "); //Message to tell user to input the password.
pass = input.nextLine(); //Taking the users password input.
//Validating the users User-name and password input.
if(user.equals("Shane") && (pass.equals("Temple"))) {
System.out.println("Correct!"); //If the User-name and password are both correct then a message will tell the user that they are correct.
}
else {
System.out.println("The Usernname or Password that you have entered was in-correct"); //If above conditions are not met then message will tell the user that they have entered the wrong user-name or password
}
}
}
I know this is extremely basic as I said I'm very new to Java (2 hours ago new).
I thought of calling the "main" method inside the else condition statement however I heard It's bas practice to use the "main" method any more times than when the program first starts.
Thanks in advance :)
I hope this is what you wanted.
import java.util.Scanner;
public class UserPass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String user; //Creating user-name variable.
String pass; //Creating password variable.
boolean isValidUser = false;
while(!isValidUser) {
System.out.println("Enter username here: "); //Message to tell user to input the user-name.
user = input.nextLine(); //Taking the users user-name input.
System.out.println("Enter the password here: "); //Message to tell user to input the password.
pass = input.nextLine(); //Taking the users password input.
//Validating the users User-name and password input.
if(user.equals("Shane") && (pass.equals("Temple"))) {
System.out.println("Correct!");
isValidUser = true;
}
else {
System.out.println("The Usernname or Password that you have entered was in-correct");
isValidUser = false;
}
}
}
}

How to validate input string using while loop

I know this might seem like a simple/silly question, but I am trying to keep my code as organized and simple as possible. The problem that I am having is with a while loop for validation. I am validating a string input. I am using the validation simply to make sure that something is entered. The only time I would like the while loop to run is when no information is entered at all, so I would like to include every character and symbol. The question that I have, is that I am wondering if there is a shorter way to include every character possible except for simply hitting enter of course. Here is the simple code snippet.
Scanner input = new Scanner(System.in);
PrintWriter out = new PrintWriter("contactRequest.txt");
System.out.print("Please enter your name: ");
String email = input.nextLine();
while(!email.matches("[a-zA-Z]+"));
{
System.out.println("\nPlease enter a valid E-Mail.");
email = input.nextLine();
}
out.println("E-Mail: " + email);
What about restructuring it as a do-while and only having one print/scan?
Scanner input = new Scanner(System.in);
PrintWriter out = new PrintWriter("contactRequest.txt");
String email;
String prompt = "Please enter your name: ";
do {
System.out.print(prompt);
email = input.nextLine();
prompt = "\nPlease enter a valid E-Mail.\n"
} while (!email.matches("[a-zA-Z]+"));
out.println("E-Mail: " + email);

while loop error in Java

well im currently learning java my myself but from what i know i just cant seem to fix this problem
currently testing a script where if u dont type ur name exactly u must re-type it but this error appears i searched everywhere but most of the things i tried dont work
Please type in your name:
lucas
Welcome lucas
Confirm your name:
luca
Please type in your name:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at input.main(input.java:9)
here is the code:
import java.util.Scanner;
public class input {
public static void main(String[] args) {
while (true) {
try (Scanner input = new Scanner(System.in)) {
System.out.println("Please type in your name: ");
String name = input.nextLine();
System.out.println("Welcome " + name);
if (name.equals("nico")) {
System.out.println("bitch");
break;
} else {
System.out.println("Confirm your name:");
String name1 = input.nextLine();
if (name1.equals("nico")) {
System.out.println("Hello " + name1 + "... bitch");
} else if (name1.equals(name)) {
System.out.println("Thank you");
break;
}
}
}
}
}
}
Move the try-with-resources to around your while loop. When execution leaves the try-with-resources, Java closes the resources. Here, that resource is the standard input, which cannot be re-opened.
try (Scanner input = new Scanner(System.in)) {
while (true) {
System.out.println("Please type in your name: ");
You actually don't really need the try-with-resources here. Don't close standard input/output/error.
Don't put the Scanner into your loop.
Loop while the scanner still has input.
Currently, you create new Scanner too often.

Categories