This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I'm new to Java and i decided to experiment, however I'm having hard time trying to understand what is the problem. What my program is supposed to do is to receive login and login2, password and password2, and if they match then program says "You may enter", if not then program says "You may not enter", however, it says it even when login and login2, password and password2 are the same. Any ideas what to do?
public static void main(String args[]) {
Scanner input = new Scanner (System.in);
System.out.println("In order to register type your login");
String login = input.nextLine();
System.out.println("And password");
String password = input.nextLine();
System.out.println("Enter Login");
String login2 = input.nextLine();
System.out.println("Enter password");
String password2 = input.nextLine();
if (login == login2 && password == password2){
System.out.println("You may enter");
}
else{
System.out.println("You may not enter");
}
}
A String is an Object in java. You have to compare it with .equals() or .equalsIgnoreCase().
if (login.equals(login2) && password.equals(password2)){
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I have a rudimentary piece of code that's meant to update a properties file. However, it seems that of the two possible keywords to update, only the second is updated by the user's input, as opposed to one after the other.
Here is the full code:
import java.io.*;
import java.util.Properties;
import java.util.Scanner;
public class UpdateProperty{
private static int choice;
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws Exception
{
FileInputStream in = new FileInputStream("Stats.properties");
Properties props = new Properties(); //creates a Properties object named prop
props.load(in); //loads in as value of prop
in.close(); //no idea
System.out.println("1- BlackBerryIzzie: " + props.getProperty("BlackBerryIzzie"));
System.out.println("2- GrapeFruitIzzie: " + props.getProperty("GrapeFruitIzzie"));
System.out.println("");
String blackAmount = props.getProperty("BlackBerryIzzie");
String grapeAmount = props.getProperty("GrapeFruitIzzie");
//System.out.println("Selling BlackBerry Izzie");
//blackAmount = itemSold(blackAmount);
System.out.println("Do you wish to update inventory? Type 2");
choice = sc.nextInt();
if (choice == 2){
FileOutputStream out = new FileOutputStream("Stats.properties");
System.out.println("Insert BlackBerry Amount");
blackAmount = sc.nextLine();
props.setProperty("BlackBerryIzzie", blackAmount);
System.out.println("Insert GrapeFruit Amount");
grapeAmount = sc.nextLine();
props.setProperty("GrapeFruitIzzie", grapeAmount);
props.store(out, null);
out.close();
}
}
public static String itemSold(String s){
int i=Integer.parseInt(s);
i -= 1;
String ret=Integer.toString(i);
return ret;
}
}
The bit that seems to be malfunctioning:
if (choice == 2){
FileOutputStream out = new FileOutputStream("Stats.properties");
System.out.println("Insert BlackBerry Amount");
blackAmount = sc.nextLine();
props.setProperty("BlackBerryIzzie", blackAmount);
System.out.println("Insert GrapeFruit Amount");
grapeAmount = sc.nextLine();
props.setProperty("GrapeFruitIzzie", grapeAmount);
props.store(out, null);
out.close();
}
This is meant to ask the user for blackberry amount, then update the BlackBerryIzzie keyword to that amount. Then, it is meant to do the same for grapefruit after blackberry is done. However, it skips blackberry and only asks for one scanner input and sets grapefruit to that.
Thanks for your time!
Don't mix nextLine and nextAnythingElse.
The solution is to set your scanner's delimiter to what you want. You want 'user presses enter' to be the delimiter, surely. So, tell scanner that. Run scanner.useDelimiter("\\R") immediately after making it. Then, to get 'an entire line', call .next(), if you want that line to be read as e.g. an int, call .nextInt(), etc. Don't call nextLine() for anything.
Explaining why mixing nextLine and nextAnythingElse is bad is a bit of a story - this SO answer explains part of it. Unfortunately the 1000-vote accepted answer is not the right solution (.useDelimiter("\\R") and then .next() to read a line is the right solution).
Question:
create a class named Account that contains the string fields name, email and
password.
Develop a program called LoginSim that simulates a login procedure.
The program reads a list of names, email addresses and passwords from a file pw.txt.
Store the information in an ArrayList of Account objects.
*Note: for Netbeans users the file must be placed in a test folder and accessed with new File("test/pw.txt");
Your program will prompt the user for their email address.
If the email is not in the system, prompt the user to try again. Give them an option to quit.
If the email is found in the system, prompt the user to enter their password.
After 3
unsuccessful tries, inform the user that they are locked out and end the program.
If the password matches, welcome the user by name and ask if they would like to change their
password.
If so, prompt for the new password and change it accordingly. If not, end the
program by confirming that they have signed out.
When the program ends, display the list of accounts.
Sample output:
Enter your email address (q to quit):
draco#hogwarts.com
Email not found, please try again (q to quit):
dmalfoy#hogwarts.com
Email not found, please try again (q to quit):
q
Goodbye!
pw.txt
Hagrid hagrid#hogwarts.com 111
Harry harry#hogwarts.com killvoldy777
Ron ron#hogwarts.com mypassword123
Hermione hermione#hogwarts.com 98fJG83h*4iwrej!
What should I do next, exception at line 16
import java.util.*;
import java.io.*;
public class LoginSim {
private static int index;
public static void main(String args[]) throws
FileNotFoundException, ArrayIndexOutOfBoundsException {
String em;
String pw;
Scanner f = new Scanner(new File("src/pw.txt"));
Scanner kb = new Scanner(System.in);
String[] email = new String[3];
String[] password = new String[3];
int i = 0;
while (f.hasNext()) {
email[i] = String.valueOf(f.hasNext());
password[i] = String.valueOf(f.hasNext());
i++;
}
System.out.println("Enter Email:");
em = kb.next();
System.out.println("Enter Password:");
pw = kb.next();
if (index != -1) {
System.out.println("Enter pw:");
pw = kb.next();
int tries = 0;
while (!pw.equals(tries < 2) &&
!pw.equals(password[index])) {
System.out.println("Incorrect Password, Try Again");
tries++;
pw = kb.next();
}
if (pw.equals(password[index])) {
System.out.println("Successful Login");
}else {
System.out.println("3 Strikes, Locked out");
}
System.out.println("Email not found");
}
}
}
Ok, you are getting java.lang.ArrayIndexOutOfBoundsException: 3 in this line email[i] = String.valueOf(f.hasNext()); because the size of your array is 3 (String[] email = new String[3];), but you are trying to add more then 3 entries to it, at least 4 based on your sample "pw.txt".
Also, you have the same issue with your password array.
I built a simple java app. However, I can't understand how could I secure this app to avoid hard-coded passwords that a decompiler won't be able to reveal.
LoginMain
import java.util.Scanner;
public class LoginMain {
public static void main(String[] args) {
String Username;
String Password;
Password = "admin";
Username = "admin";
Scanner input1 = new Scanner(System.in);
System.out.println("Enter Username : ");
String username = input1.next();
Scanner input2 = new Scanner(System.in);
System.out.println("Enter Password : ");
String password = input2.next();
if (username.equals(Username) && password.equals(Password)) {
System.out.println("Access Granted! Welcome!");
} else if (username.equals(Username)) {
System.out.println("Invalid Password!");
} else if (password.equals(Password)) {
System.out.println("Invalid Username!");
} else {
System.out.println("Invalid Username & Password!");
}
}
}
LoginNew.java
import java.util.Scanner;
public class LoginNew {
public static void main(String[] args) {
String Username;
String Password;
Scanner scan = new Scanner (new File("1.txt"));
Scanner input1 = new Scanner(System.in);
System.out.println("Enter Username : ");
String username = input1.next();
Scanner input2 = new Scanner(System.in);
System.out.println("Enter Password : ");
String password = input2.next();
if (username.equals(Username) && password.equals(Password)) {
System.out.println("Access Granted! Welcome!");
} else if (username.equals(Username)) {
System.out.println("Invalid Password!");
} else if (password.equals(Password)) {
System.out.println("Invalid Username!");
} else {
System.out.println("Invalid Username & Password!");
}
}
}
However, the system presents me :
loginNew.java:9: error: cannot find symbol
Scanner scan = new Scanner (new File("1.txt"));
^
symbol: class File
location: class loginNew
1 error
Error: Could not find or load main class loginNew
I created the file 1.txt with my credentials: Password = "admin";
Username = "admin"; Simple stuff but Im lost. sorry..
Normally, passwords wouldn't even be stored in the application code - they'd be validated against a database or some other data source. But throwing those concerns aside for a moment...
The answer to your question is to use a one-way hash. That is, encrypt the password with a hash function that can't be reversed. When the user types in a password, hash it and compare it to the hash that's stored in your application code. (Replace the password variable with a passwordHash variable.) Because the hash can't be (easily) decrypted, it's more secure than storing the plain-text password in your application source (or database, or wherever else you may be storing hashed passwords).
As others have alluded to, cryptographic hashing (and application security) can get complex very quickly, and isn't particularly friendly for beginners to work with. So this answer might help you understand some concepts, but you might need a bit more to secure a production-quality application.
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
import java.util.Scanner;
public class Box
{
public static void main(String[] args)
{
String empty = "";
String yes = "yes";
String no = "no";
String response;
String name;
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name >>");
name = input.nextLine();
if(name.equals(empty))
{
System.out.println("You did not enter a name, please try again >>");
name = input.nextLine();
}
System.out.println("Would you like the profanity filter turned on?");
response = input.nextLine();
response = response.toLowerCase();
if(response.equals(yes) || response.equals(no))
{
if(response.equals(yes))
System.out.print("Profanity filter will be turned on.");
else
System.out.print("Profanity filter will not be turned on.");
}
else
System.out.print("Invalid response, please try again.");
}
}
This displays "Please enter your name >>", but no matter what I enter there, even if it's empty, it always asks if you'd like the profanity filter turned on.
It just skips over the if that's supposed to loop forever until you actually enter a name, and I can't figure out why.
Also, I know I didn't ask this in the title, but I also can't figure out a way for the final statement to loop back to the "response = input.nextLine();" when someone doesn't enter either "yes" or "no".
If you want it to loop forever then you need to use while loop and not if, e.g.:
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name >>");
String name = input.nextLine();
while(name.isEmpty()){
System.out.println("You did not enter a name, please try again >>");
name = input.nextLine();
}
This will keep asking the user to enter the name until he enters a non empty String.
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I am just learning HashMaps, and have just written my first program using them. For some reason, my check to determine if the inputs I've entered match up with the key and it's corresponding value always returns false. Can anyone tell me why that is?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
public class Exercise {
public static void main(String[] args) throws FileNotFoundException {
HashMap<String, String> userPass = new HashMap<String,String>();
HashMap<String, String> userFull = new HashMap<String, String>();
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the filename to read from: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()){
String fullname=inputFile.next()+" "+inputFile.next();
String username=inputFile.next();
String pass=inputFile.nextLine();
userPass.put(username, pass);
userFull.put(username, fullname);
}
inputFile.close();
//initialize variable for use after loop
String inputUsr = null;
//checks if key/value is found
boolean b=false;
int tries=1;
while(b==false){
System.out.print("Login: ");
inputUsr=keyboard.next();
System.out.print("\nPassword: ");
String inputPass=keyboard.next();
//if inputted password equals the password of the inputted username
if(inputPass.equals(userPass.get(inputUsr)))
b=true;
System.out.println("Either the username or password is incorrect. You have "+(3-tries)+" more attempts.");
tries++;
//program quits afte 3 tries
if(tries>3){
System.exit(0);
}
}
System.out.println("Welcome "+userFull.get(inputUsr));
}
}
There are two problems in the code inside your while loop as explained below:
(1) keyboard.next() is reading the console output text i.e., reading the printed text 'Password', so replace keyboard.next() with keyboard.nextLine();
(2) You did not handle the else condition for the tries count
You can refer at the below code with inline comments:
while(b==false){
System.out.print("Login: ");
inputUsr=keyboard.nextLine();
System.out.print("\nPassword: ");
String inputPass=keyboard.nextLine();
if(inputPass.equals(userPass.get(inputUsr))) {
b=true;
} else {
System.out.println("Either the username
or password is incorrect.
You have "+(3-tries)+" more attempts.");
tries++;
}
if(tries>3){
System.exit(0);
}
}