Check for key in hash maps while checking user input - java

I am trying to compare the key values of a hashmap with user input but I'm not sure of what approach should be taken.
This is the current code I have:
Scanner scan = new Scanner(System.in);
System.out.println("Type an instruction from the list \n 1. hello \n 2. goodbye");
String input = scan.nextLine();
HashMap helloMap = new HashMap<>();
helloMap.put("hello", "you typed hello");
HashMap goodbyeMap = new HashMap<>();
goodbyeMap.put("goodbe", "you typed goodbye");
if(input.equals(helloMap)){
String helloOutput = (String) helloMap.get("hello");
System.out.println(helloOutput);
}
else if (input.equals(goodbyeMap)){
String goodbyeOutput = (String) goodbyeMap.get("goodbye");
System.out.println(goodbyeOutput);
}
else{
System.out.println("Invalid input");
}
The issue that I've ran into is that when I try to use this program it always defaults to the else clause and this is because I'm used to using .equals to compare it to a String value but I know this is different! Does anyone know the solution for this? Ok so I found a solution for it... It works but is it good enough?
String goodbyeCommand = String.valueOf(goodbyeMap.keySet()).replace("[^a-zA-Z0-9]", "").trim();
String helloCommand = String.valueOf(helloMap.keySet()).replaceAll("[^a-zA-Z0-9]", "").trim();

The problem
You are comparing the input String with the HashMap object. String object is not equal to HashMap object, which is why the boolean expression is always false.
The solution
Please have a look at the following sample:
Map<String, String> outputMap = new HashMap<>();
outputMap.put("hello", "you typed hello");
outputMap.put("goodbye", "you typed goodbye");
System.out.println("Type an instruction from the list \n 1. hello \n 2. goodbye");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
scan.close();
String output = outputMap.get(input);
if (output == null) {
System.out.println("Invalid input");
} else {
System.out.println(output);
}
Breakdown
We define a Map<String, String> containing the program's response mapped to predefined user inputs.
We ask the user for input. When you are done using Scanner, it is good practice to close it by calling .close().
We retrieve the response from the map based on the user input.
We check for null: if it is null, it means the user input was not a valid key for outputMap.
Print the result.

Yes, you need to compare to the actual element of your map instead of the map itself:
Scanner scan = new Scanner(System.in);
System.out.println("Type an instruction from the list \n 1. hello \n 2. goodbye");
String input = scan.nextLine();
HashMap helloMap = new HashMap<>();
helloMap.put("hello", "you typed hello");
HashMap goodbyeMap = new HashMap<>();
goodbyeMap.put("goodbe", "you typed goodbye");
if(input.equals(helloMap.get("hello"))){
String helloOutput = (String) helloMap.get("hello");
System.out.println(helloOutput);
}
else if (input.equals(goodbyeMap.get("goodbe"))){
String goodbyeOutput = (String) goodbyeMap.get("goodbye");
System.out.println(goodbyeOutput);
}
else{
System.out.println("Invalid input");
}

Related

How to verify OTP in Java using simple loop?

I'm a Java beginner and my project consists of creating a simple program to register users for an alumni center. The process creates an ID and then provides the new user with an OTP. Next is the login (Enter ID:, Enter OTP: ).
My OTP verification method is not working. It seems to be a problem with the IF.equals declaration, the process jumps straight to the ELSE condition.
Any suggestions why?
Here is my code:
class Main {
static NewRegandLogin newRegAndLogin = new NewRegandLogin(null, null, null, null, null, null);
static ArrayList<NewRegandLogin> loginInformation = new ArrayList<>();
public static void main(String[] args) {
System.out.println(" WELCOME TO THE ALUMNI SHE-CODES SYSTEM ");
System.out.println("_________________________________\n - New Alumni registration - \n");
System.out.println("");
newRegAndLogin.registerNewGrad();
System.out.println();
System.out.println("_________________________________");
System.out.println();
System.out.println("Your new Alumni ID is: " + newRegAndLogin.getAlumniId());
System.out.println();
System.out.println("Your temporary password is:");
System.out.println(newRegAndLogin.oTp(8));
loginInformation.add(newRegAndLogin);
System.out.println("_________________________________");
System.out.println("_________________________________\n - Alumni Login - \n");
System.out.println("");
newRegAndLogin.login();
System.out.println("");
System.out.println("Please make a list of completed Courses: -->Enter 'S' to stop adding courses<--");
newRegAndLogin.setAlumniCourses();
System.out.println("_________________________________");
newRegAndLogin.setLinkedInPage();
loginInformation.add(newRegAndLogin);
//printAlumniProfile();
System.out.println("_________________________________");
newRegAndLogin.jobOffer();
}
void login() {
System.out.print("ID: ");
alumniIdImput = scanner.nextLine();
idVerification();
do {
System.out.println("Password (OTP if logging in for the first time): ");
passwordImput = scanner.nextLine();
oTpFromImput = passwordImput.toCharArray();
oTpVerification();
} while (isPasswordCorrect=false);
void oTpVerification() {
isPasswordCorrect = false;
if (oTpFromImput.equals(oTp(8))) {
isPasswordCorrect = true;
System.out.println("Logging In.....");
}else {
isPasswordCorrect = false;
System.out.println("Incorrect password.\nPlease enter valid password: 8 alpha numeric
characters(Aa,123,#,#,$,%)");
}
}
This is the oTp method
char[] oTp (int length) {
String capitalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String smallChars = "abcdefghijklmnopqrstuvwxyz";
String numbers = "0123456789";
String symbols = "!##$%^&*_-=+/.?<>";
String values = capitalChars + smallChars + numbers + symbols;
Random oneTimePassword = new Random();
char[] password = new char[length];
for(int i = 0; i<length;i++) {
password[i] = values.charAt(oneTimePassword.nextInt(values.length()));
}
return password;
}
It seems you built a guessing game, not an OTP verification code.
You first read the OTP from user, and only then randomly generate one to copare to it.
Basically, you code expects the user to guess a random 8 character password that has not been created you, which is basically impossible...
You need to generate to OTP first, show it to the user, then ask them to input it.
I see your logic code is generate OTP code after User input. It seem so wierd bro.
Whenever you call oTp(8) function will generate new OTP.
Use should generate OTP first then store somewhere, then User input and compare it.
You need to store the generated otp somewhere. Then compare it with the input otp. Right now you are comparing it with the otp(8). And otp(8) always returns a new otp.

How to check the user input is an integer or not with Scanner?

I want the country codes are integer that input by the user. I want an error message to be show when user inputs a code which is not an integer. How can I do this? The program is to ask user to enter country name and country code. In which user will input the country code. But if user inputs a character I want a message to be shown saying Invalid Input.
System.out.println("Enter country name:");
countryName = in.nextLine();
System.out.println("Enter country code:");
int codeNumber = in.nextInt();
in.nextLine();
If the input is not an int value, then Scanner's nextInt() (look here for API) method throws InputMismatchException, which you can catch and then ask the user to re-enter the 'country code' again as shown below:
Scanner in = new Scanner(System.in);
boolean isNumeric = false;//This will be set to true when numeric val entered
while(!isNumeric)
try {
System.out.println("Enter country code:");
int codeNumber = in.nextInt();
in.nextLine();
isNumeric = true;//numeric value entered, so break the while loop
System.out.println("codeNumber ::"+codeNumber);
} catch(InputMismatchException ime) {
//Display Error message
System.out.println("Invalid character found,
Please enter numeric values only !!");
in.nextLine();//Advance the scanner
}
One simple way of doing it, is reading a line for the numbers as you did with the name, and then checking witha Regex (Regular Expression) to see if contains only numbers, with the matches method of string, codeNumber.matches("\\d+"), it returns a boolean if is false, then it's not a number and you can print your error message.
System.out.println("Enter country name:");
countryName = in.nextLine();
System.out.println("Enter country code:");
String codeNumber = in.nextLine();
if (codeNumber.matches("\\d+")){
// is a number
} else {
System.out.println("Please, inform only numbers");
}
You can do something like this, by first getting the input as a string, then try to convert the string to an integer, then outputs an error message if it can't:
String code= in.nextLine();
try
{
// the String to int conversion happens here
int codeNumber = Integer.parseInt(code);
}
catch (NumberFormatException nfe)
{
System.out.println("Invalid Input. NumberFormatException: " + nfe.getMessage());
}
You could instead check hasNextInt then call nextInt
int codeNumber;
System.out.println("Enter country code:");
if(in.hasNextInt())
{
codeNumber = in.nextInt();
}
else
{
System.out.println("Invalid Code !!");
}
If you are creating your own custom exception class, then use regex to check if the input string is an integer or not.
private final String regex = "[0-9]";
Then, check if the input follows the regex pattern.
if (codeNumber.matches(regex)) {
// do stuff.
} else {
throw new InputMismatchException(codeNumber);
}
You can use build in InputMismatchException if you are not creating your custom exception handler.

How to make do while loop after validating email address?

// My Scanner
Scanner input = new Scanner(System.in);
//using Do While Loop
do {
//Asking user to enter email
System.out.println("enter your email:");
//Read and safe input in to Var userEmail
String userEmail = input.next();
//Check for contains '#' and '.com' simbols
Pattern pattern = Pattern.compile("\\S+?#\\S+?\\.com");
//And it checking in users entered email
Matcher matcher = pattern.matcher(userEmail);
//if userEmail contain '#'and '.com' print next line
if (matcher.matches()) {
System.out.println("Matches"); // Prints this for this email
}
//if user put email with out '#'and'.com' print next line
else {
System.out.println("your email should
looks like this sample bob.Dillon#gmail.com");
}
// And here I have a problem don't know what to type in
// so that it starts looping until user input will be 100% correct.
} while(!matcher.matches());
Can someone help what needs to be done here while(here); to make it looping?
You want to see if the user entered anything in those fields. So, check like this:
if (INPUTVALUE.length > 0) { //THEY ENTERED SOMETHING
// do something
}
Then, put this in your while statement. Like so:
// My Scanner
Scanner input = new Scanner(System.in);
//using Do While Loop
do{
//Asking user to enter email
System.out.println("enter your email:");
//Read and safe input in to Var userEmail
String userEmail = input.next();
//Check for contains '#' and '.com' simbols
Pattern pattern = Pattern.compile("\\S+?#\\S+?\\.com");
//And it checking in users entered email
Matcher matcher = pattern.matcher(userEmail);
//if userEmail contain '#'and '.com' print next line
if (matcher.matches()) {
System.out.println("Matches"); // Prints this for this email
}
//if user put email with out '#'and'.com' print next line
else{
System.out.println("your email should
looks like this sample bob.Dillon#gmail.com");
}
//And here I have a problem don't know what to type in so that it starts looping until user input will be 100% correct
}while(INPUTVALUE.length > 0);
You need:
}while(INPUTVALUE.length > 0);
To break the loop:
Just erase all of the values that the user has entered at the end of the do. That way, INPUTVALUE.length < 0. That will break the loop ! Good luck !

I need help on the Java Scanner Code

So I need help on this code. This code is all in one so ignore the spaces but I need to write another scanner in the way bottom of the code and if I do add
String feeling = in.nextLine(); at the very end it does not work. I need a it so that I can write my feelings so that I can make jarvis answer but the string does not work and java ignores the string and goes right on to the next part. It starts from the middle.
Scanner in = new Scanner(System.in);
System.out.println("Type User Name:");
String userName = in.nextLine();
System.out.println("PASSWORD:");
int passcodeFromUser=in.nextInt();
int passcode = 2015;
if (passcodeFromUser == passcode) {
System.out.println("Welcome Mr." + userName + "!");
Random random = new Random(userName.hashCode());
System.out.println("Mr." + userName + ", You are now recognized and you are now able to command me.");
System.out.println("I was created by John Choi");
System.out.println("JARVIS stands for Just A Rather Very Intelligent System");
System.out.println("How are you today Mr." + userName + "?");
}
So if I add this code at the back it does not work. It ignores and says Oh. Mr is feeling.
String feeling = in.nextLine();
System.out.println("Oh. Mr." + userName + "is feeling" + feeling + ".")
That is because your nextInt invocation does not actually parse a line feed.
Quoting the API, Scanner#nextInt:
Scans the next token of the input as an int.
(focus on the token part here)
Here's one (but not the only) way to fix it:
Integer passcodeFromUser = null;
try {
passcodeFromUser= Integer.parseInt(in.nextLine());
}
catch (NumberFormatException nfe) {
// TODO handle non-numeric password
}
... instead of int passcodeFromUser=in.nextInt();.
You can also loop the parsing of the Integer so that you print an error message when catching the NumberFormatException and don't break the loop until you have a valid numeric passcode.
You can consume the \n character:
in.nextLine();
String feeling = in.nextLine();
So just putting in.nextLine() before the code you were going to add will easily fix your problem.

Make an email list, by entering only recipient names

I want to make a simple code, that prompts you to enter names, separated by comma or just a space, and when you click enter, to take every one word you entered, and put a #gmail.com at the end of it, how can I do it?
That's what I have for now
Scanner input = new Scanner(System.in);
String mail = "#gmail.com";
String names;
System.out.println("Enter names: ");
names = input.next();
System.out.println(names + mail);
This should be everything you asked for, if you put a list of names separated by commas it will loop through them, otherwise it will just print a single name.
Scanner input = new Scanner(System.in);
String mail = "#gmail.com";
System.out.println("Enter names: ");
String names = input.next();
if(names.contains(",")) {
for(String name : names.split(",")) {
System.out.println(name + mail);
}
} else {
System.out.println(names + mail);
}
Hope that helps.
Not knowing what language this is, here's the pseudo-code:
names = input.next();
namesArray = names.split(" ") -- replace with your preferred delimiter
foreach name in namesArray
print name + mail

Categories