Program prints menu twice in a row - java

I'm making a credential like program and it is very WIP. I placed a while loop with a Boolean condition to make the program run again whenever a person finishes creating a credential, but when it loops to the beginning of the program it prints the first part twice! like this:
run:
|-----------------------------------------------|
|Welcome to the Credential Managing System 2013!|
|-----------------------------------------------|
Would you like to create or manage a credential?
Choose: Manage | Create
Waiting for input: Create
Credential name: df
Credential ID: 34243
Credential Password: numbers or words?
Waiting for input: numbers
Credential Password: 13651
|-------------------|
|Credential created!|
|-------------------|
Would you like to create or manage a credential?
Choose: Manage | Create
Waiting for input:
from there it stops reading the input again.
here is the entire code!
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Carlinhos
*/
import java.util.Scanner;
public class Criação {
public static void main(String[] args){
Scanner e = new Scanner(System.in);
System.out.println(" |-----------------------------------------------|");
System.out.println(" |Welcome to the Credential Managing System 2013!|");
System.out.println(" |-----------------------------------------------|");
System.out.println("");
Boolean autoRun = true;
while(autoRun){
System.out.println(" Would you like to create or manage a credential?");
System.out.println("");
System.out.println(" Choose: Manage | Create");
System.out.println("");
System.out.print(" Waiting for input: ");
String op1 = e.nextLine();
autoRun = false;
if(op1.equals("Create")){
System.out.println();
System.out.print("Credential name: ");
String credName = e.nextLine();
System.out.print("Credential ID: ");
int credID = e.nextInt();
System.out.println("Credential Password: numbers or words?");
System.out.print("Waiting for input: ");
e.nextLine();
String credPassCheck = e.nextLine();
if(credPassCheck.equals("numbers")){
System.out.print("Credential Password: ");
double credPassNum = e.nextDouble();
}
else if(credPassCheck.equals("words")){
System.out.print("Credential Password: ");
String credPassLet = e.nextLine();
}
System.out.println("");
System.out.println(" |-------------------|");
System.out.println(" |Credential created!|");
System.out.println(" |-------------------|");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
autoRun = true;
}
}
}
}

Change this line:
while(autoRun = true)
to this:
while(autoRun)
= is not the equality comparison operator, it's the assignment operator. So, when you check that condition autoRun is the assigned the value true even though you set it to false earlier. You can use == instead but since autoRun is a boolean variable, you can simply use this variable without comparing it to anything else.
UPDATE:
After OP's comments that the program has started exiting after printing the prompt for the second time, I looked into the code a little more and found these lines:
if(credPassCheck.equals("numbers")){
System.out.print("Credential Password: ");
double credPassNum = e.nextDouble();
}
This is basically consuming less input than is necessary and thus the next prompt for "Waiting for Input" gets a single newline character as its input. The fix should be obvious now:
if(credPassCheck.equals("numbers")){
System.out.print("Credential Password: ");
double credPassNum = e.nextDouble();
e.nextLine(); //Add this Line
}

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.

Assert Exception message not showing

Hi I'm currently working on an assignment where I have to check if the Resident Password matches with the Door password or not, I have to give the user three tries and after that use assert to show to tell the user to try again. this is my code but the assert is not showing any message.
public static void main(String[] args) throws Exception {
// write your code here
Scanner s = new Scanner(System.in);
String P, pas;
int i = 0;
while (i <= 2) {
System.out.println("Enter Resident Password: ");
pas = s.next();
System.out.println("Enter Door Password: ");
P = s.next();
Resident r = new Resident("XYZ", pas);
Door d = new Door(P);
Dorm D = new Dorm();
D.Check();
if (Resident.getPassword().equals(Door.getPassword())) {
System.exit(0);
} else {
i++;
}
}
assert i>2 : "Serious Error – Program has been terminated Try again later";
}
what should I do to get the message using assert.
From https://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html#enable-disable
By default, assertions are disabled at runtime. Two command-line switches allow you to selectively enable or disable assertions. To enable assertions at various granularities, use the -enableassertions, or -ea, switch
The way assert works with sending an error message is via using ensuring the condition fails in the case you want. For example:
assert <condition> : <message-if-condition-is-false>;
So if you change your assert to use:
assert i<=2 : "Serious Error – Program has been terminated Try again later";
You throw if i is still <=2. If the condition fails, then the message gets thrown as AssertionError.
So with the above, if I execute it as:
javac Example.java
java -ea Example
and give the desired wrong inputs, you would get:
Exception in thread "main" java.lang.AssertionError: Serious Error, Program has been terminated Try again later
Anyhow, you could choose to use System.err and output the error message:
public static void main(String[] args) throws Exception {
// Write your code here
Scanner s = new Scanner(System.in);
String P, pas;
int i = 0;
while (i <= 2) {
System.out.println("Enter Resident Password: ");
pas = s.next();
System.out.println("Enter Door Password: ");
P = s.next();
Resident r = new Resident("XYZ", pas);
Door d = new Door(P);
Dorm D = new Dorm();
D.Check();
if (Resident.getPassword().equals(Door.getPassword())) {
System.exit(0);
} else {
i++;
}
}
// This need not be verified with if (i>2) because the System.exit(0); will exit if the condition satisfies
System.err.println("Serious Error – Program has been terminated Try again later");
}

ArrayList Printing

I have an assignment to create an ArrayList of employees, to provide a menu to add, find, and delete employee records. I successfully managed to implement all the functions on my own, but there is a small problem. When I use the find or delete option, the correct record is found or deleted properly but the code goes through the array list of elements and prints out employee not found till the correct record is found, this is unnecessary as it should only print the found record. I have limited experience with coding and I am writing my own code from scratch, please help me with this.
enter image description here
I'VE ATTACHED MY CODE AND THE OUTPUT!
else if (choice.equals("4")) {
System.out.println("Enter Name: ");
String fName = myScanner.nextLine();
System.out.println("Enter Job Name: ");
String fJob = myScanner.nextLine();
for (int i = 0; i < myEList.size(); i++) {
if (myEList.get(i).getName().equals(fName) && myEList.get(i).getJob().equals(fJob)) {
System.out.println("Employee found!");
System.out.println(myEList.get(i).toString());
} else {
System.out.print("Employee not found!");
}
}
} else if (choice.equals("5")) {
System.out.println("Enter Name: ");
String dName = myScanner.nextLine();
System.out.println("Enter Job Name: ");
String dJob = myScanner.nextLine();
for (int i = 0; i < myEList.size(); i++) {
if (myEList.get(i).getName().equals(dName) && myEList.get(i).getJob().equals(dJob)) {
System.out.println("Employee record removed succesfully!");
myEList.remove(i);
} else {
System.out.print("Employee not found!");
}
}
}
This is the Output
Enter Option: 4
Enter Name: arjun
Enter Job Name: tester
Searching...
Employee not found!
Employee not found!
Employee found!
Name: arjun Job Name: tester Weekly Pay: 1200.0
else
{
System.out.print("Employee not found!");
}
This has to be AFTER the for loops are over. You need a found flag. If after the loop is false then print the message
Create a variable to track if employee not found before the loops
In the if statements sent it to false if found.
At the end of the loop check if it is true. Then print the message "Employee not found"
See the sample below
boolean notFound = true;
for(int i=0;i<myEList.size();i++)
{
if(myEList.get(i).getName().equals(fName)&&myEList.get(i).getJob().equals(fJob))
{
System.out.println("Employee found!");
System.out.println(myEList.get(i).toString());
notFound = false;
break;
}
}
if(notFound)
System.out.print("Employee not found!");
Remove this block of code
else
{
System.out.print("Employee not found!");
}
It should work fine after that.
EDIT
This is off topic but when you ask question next time remember to post image of output rather than typing it or posting a link.
And also avoid writing about your coding experience. Just be straight to the point. It just increases the size of question unnecessarily. :)

Generating username with given information from the user

Hi Im Can Somebody help me with my program ?
my professor ask us to do a program that will get information from the user and generate a 6 letter username from the lastname and firstname of the user.
the first 3 letters of the user name is the first 3 letters of the firstname and the other 3 is the last 3 letters of the lastname of the user. and we need to test it by log-in module
to test if the username and password are match on the generated username and user inputted password
As far as im doing i cant find a answer on this and our professor didn't teach us about this this and im struggling right now.
this is my program right now>>>
public static InputStreamReader r = new InputStreamReader(System.in);
public static BufferedReader i = new BufferedReader(r);
public static void main(String[]args) throws Exception{
String Lname,Fname,Mi;
int age,bday;
float pass;
System.out.print("Enter Last Name: ");
Lname=i.readLine();
System.out.print("Enter First Name: ");
Fname=i.readLine();
System.out.print("Enter Middle Name: ");
Mi=i.readLine();
System.out.print("Age: ");
age=Integer.parseInt(i.readLine());
System.out.print("Birthday (MM/DD/YY) :");
bday=Integer.parseInt(i.readLine());
System.out.println("Password Must Be A 4-6 Digit Combination");
System.out.print("Enter Password : ");
pass=Float.parseFloat(i.readLine());
System.out.println("Please Wait While Generating Your UserName");
for(int j=0;j<=35;j++)
{
try{
Thread.sleep(100);
}
catch(InterruptedException ex)
{
//do nothing
}
System.out.print("*");
}
}
Can Somebody Help Me Please....
You can just:
String username = FName.substring(0,3) + LName.substring(LName.length() - 3, LName.length());
You should probably check that FName and LName have a minimum length of 3 characters, or you will get an exception

How to read Strings with spaces inside while loop (Java)

This always gives me a headache. I am trying to read and save multiple-word Strings for the fields "name" and "malady" within a while loop. Here is my code:
while(OR1.isFull() == false || OR2.isFull() == false)
{
// prompt for next request
System.out.println("Enter patient info:");
// read patient info
System.out.print("Name: ");
String name = input.nextLine();
input.nextLine();
System.out.print("Malady: ");
String malady = input.nextLine();
input.nextLine();
System.out.print("Priority: ");
int priority = input.nextInt();
// store patient info
Patient patient = new Patient(name, malady, priority);
OR1.add(patient);
} // end while
System.out.println("List of patients scheduled for Operating Room 1");
while(OR1.isEmpty() == false)
{
// pop and print root
System.out.print(OR1.remove());
}
And here is what my console input and output looks like:
Enter patient info:
Name: John Doe
Malady: Broken hip
Priority: 6
List of patients scheduled for Operating Room 1
Patient: Malady: Broken hip Priority: 6
// end console output.
Notice that it did not record the value I entered for "Name," and also that it prompted for an extra line of input after obtaining "Malady" (required me to press enter again to get it to ask for the next input, "Priority").
I have read the documentation at http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html. I have tried different combinations of next() and nextLine(). I just don't get it.
Problem solved by changing the code to the following:
// read patient info
System.out.print("Name: ");
input.nextLine();
String name = input.nextLine();
System.out.print("Malady: ");
String malady = input.nextLine();
System.out.print("Priority: ");
int priority = input.nextInt();
Though I am still confused about how this silly scanner works =/
I believe it should work for just:
// read patient info
System.out.println("Name: ");
String name = input.nextLine();
System.out.println("Malady: ");
String malady = input.nextLine();
System.out.println("Priority: ");
int priority = input.nextInt();
Perhaps the problem is in the Patient constructor or something?
Problem solved by changing the code to the following:
// read patient info
System.out.print("Name: ");
input.nextLine();
String name = input.nextLine();
System.out.print("Malady: ");
String malady = input.nextLine();
System.out.print("Priority: ");
int priority = input.nextInt();

Categories