Rerunning my program in Java - java

I am trying to make it so that if the username and / or password aren't correct, the program will run it over again, instead of just doing the print command in the else statement. I tried putting another while loop in the else statement and nesting the if statement inside that checks the username and password inside of it, but then I realized I would have to copy all the code from the if statement into the else statement, which obviously seems like it is not the correct solution and is probably very clunky. What is the right way to refer the program back to run from the start or something?
// Declare Variables
Scanner input = new Scanner(System.in);
String username;
String password;
String calculator = "calculator";
String renameUser = "renameUser";
String renamePass = "renamePass";
String getIp = "getIp";
String exit = "exit";
String command;
// Prompt User to login
System.out.println("Username: ");
username = input.nextLine();
System.out.println("Password: ");
password = input.nextLine();
if (username.equals("admin") && password.equals("admin") ) // Must use the equals method of string class to compare, == operator will NOT work.
{
System.out.println("Success! Welcome " + username + "!");
while (true) // Infinite loop using the true statement
{ command = input.nextLine();
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{ // renameUser code here
if (command.equals(renamePass))
{ // renamePass code here
if (command.equals(getIp))
{ // getIp code here
if(command.equals(exit))
{
break;
}
System.out.println("Logging out!");
}
}
}
}
}
}
else
{
System.out.println("Wrong username or password, please try again.");
}
}
}

Think about the below logic
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{
If command equals calculator then how can it equal renameUser
You should have it
if (....) {
}
else if (...) {
}
statement or as a switch statement

This snippet here is increasing the cyclomatic complexity of your software making it hard to make a decision, if you want to change that later, you have more chances to break the code than success
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{ // renameUser code here
if (command.equals(renamePass))
{ // renamePass code here
if (command.equals(getIp))
{ // getIp code here
if(command.equals(exit))
{
try to design something more like a witch case logic
Example:
switch (userInput) {
case renameUser:
renameUser();
break;
case getIp:
getIp();
break;
...
default:
break;
}

Related

Why is my String Variable empty after assigning something to it for a second time? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I am doing a project for school, and I am trying to make it to where you can set up a name for yourself while going through a series of questions asked by the computer. I want the user to be able to change their name right after assigning it if they do not like what they put down or they typed something wrong.
Right now the program assigns the name the user wants correctly the first time, but when it goes back through the loop to change it to something else the string is left blank.
Console Output
'''
import java.util.*;
public class JavaInputProdject
{
public static void main(String args[])
{
int i=0;
boolean boo = false;
int likeab = 0;
byte age;
boolean Old=false;
boolean aAge=true;
String user="User";
String un = user + "> ";
Scanner bob = new Scanner(System.in);
System.out.print("Bob> Hey User, My name is BOB.... what is your name?\n"+un);
do
{
user = bob.nextLine();
System.out.println("Bob> This is the Username you want? \""+ user +"\"(true/false)");
System.out.print(un);
if(bob.nextBoolean()==true)
{
boo = true;
un = user + "> ";
}
else
{
if(i>=3)
{
System.out.println("Bob> I realize it is kind of hard to pick a name but could you hurry up?");
}
System.out.print("Bob> Please type in a new Username\n"+un);
bob.next();
i++;
}
} while(boo==false);
}
}
'''
You need to replace the line bob.next() (near the end of the do-while loop) with bob.nextLine().
I believe that bob.next() does not consume the newline that is entered as a result of hitting the <ENTER> key after the bob.nextBoolean() call. Hence the user = bob.nextLine(); line (at the start of the do-while loop) is consuming that newline on the second and subsequent loop iterations. So replacing bob.next() with bob.nextLine() will resolve the problem.
For the sake of completeness, here is the corrected code:
import java.util.Scanner;
public class JavaInputProdject {
public static void main(String[] args) {
int i = 0;
boolean boo = false;
int likeab = 0;
byte age;
boolean Old = false;
boolean aAge = true;
String user = "User";
String un = user + "> ";
Scanner bob = new Scanner(System.in);
System.out.print("Bob> Hey User, My name is BOB.... what is your name?\n" + un);
do {
user = bob.nextLine();
System.out.println("Bob> This is the Username you want? \"" + user + "\"(true/false)");
System.out.print(un);
if (bob.nextBoolean()) {
boo = true;
un = user + "> ";
}
else {
if (i >= 3) {
System.out.println(
"Bob> I realize it is kind of hard to pick a name but could you hurry up?");
}
System.out.print("Bob> Please type in a new Username\n" + un);
bob.nextLine();
i++;
}
} while (boo == false);
}
}
Refer to Scanner is skipping nextLine() after using next() or nextFoo()?
when you want to get correct username based on false flag you doesnt init a value to user.
you should write something like this with bob.nextLine :
System.out.print("Bob> Please type in a new Username\n"+un);
user = bob.nextLine();
i++;

Validation when Creating an Account JAVA

So there is this certain part of my program where I can create an account and the created account will be inserted into my database. And I'm trying to code something where *refer to the code:
public void actionPerformed(ActionEvent e) {
String user = userField.getText().trim();
String pass = passField.getText().trim();
String conPass = confirmPass.getText().trim();
try{
// TODO Auto-generated method stub
if(e.getSource()==submit){
if (user.equals(user)&&pass.length()==0){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if the pass field is blank
else if(user.length()<5){
JOptionPane.showMessageDialog(null,"Username must be at least 5 characters!");
}
else if(user.equals(user)&&pass.equals(conPass)&&pass.length()!=0){
String sqlLogin = "insert into tblLogin (username,pssword) values ('"+user+"','"+pass+"')";;
getQuery(sqlLogin);
JOptionPane.showMessageDialog(null, "Account Successfully Created!");
create.dispose();
GUI gui = new GUI();
}//if(pass.equals(conPass))
else if(user.length()==0&&pass.length()==0){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if both fields are blank
else if (user.length()==0 &&pass.equals(pass)){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if user field is blank
else if(user.equals(user)&&pass!=conPass){
JOptionPane.showMessageDialog(null, "Password do not match!");
}//check if password and confirm pass matches
}
I dont really know how to say the problem but look in the if and else if statements, if the user meet one the those conditions, the program should print the JOptionPane thing. Except for the second else if.
You might be wondering why I put these codes at my else if
else if(user.equals(user)&&pass.equals(conPass)&&pass.length()!=0){
String sqlLogin = "insert into tblLogin (username,pssword) values ('"+user+"','"+pass+"')";;
getQuery(sqlLogin);
JOptionPane.showMessageDialog(null, "Account Successfully Created!");
create.dispose();
The reason for this is that, my program is having some logic error when I try to put it in if statement. Please help me with my code thanks :) Feel free to write a new code for me :DD
i might try something like this:
public static boolean isSet(String s){
if(s==null || "".equals(s)) return false;
return true;
}
//.... your validation here
if(isSet(user) && isSet(pass) && isSet(conPass) && pass.equals(conPass)){
//create account
}else{
//smth wrong eg. if(!pass.equals(conPass) { //wrongpass }
}

Java for loop with if statement only iterating once

I have a version of a login for an employee system i would like to make, I have a for loop which should go through the entire list of Accounts, then see if the name of an employee matches one in the list then the if statement continues, further questions asked etc... it seems to only iterate once and then stop as it will only find the first user and tell me the other accounts do not exisit, even though they do!! What am i doing wrong? Also my list contains Employees and Managers which inherit from Account, the if statement uses the getName in Account to compare if it equals to the user input. Sorry if this is ridiculously stupid/bad! thanks.
List <Account> Accounts = new LinkedList<Account>();
Here is where i populate my Account, the main method calls this and the list() is called whihc contains the problematic loop
public void add() {
Employee Geoff = new Employee("Geoff", "password1");
Manager Bob = new Manager("Bob", "password2");
Employee John = new Employee("John", "password3");
Accounts.add(Geoff);
Accounts.add(Bob);
Accounts.add(John);
list();
}
problem:
System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
for (Account a : Accounts) {
System.out.println(a);
if (a.getname().equals(empName)) {
System.out.println("\nPlease enter your passcode: ");
String code = Scan.nextLine();
if (a.check(code) == true) {
System.out.println("logged in");
}
}
System.out.println("Employee does not exist!");
login();
}
I am doing the print statement in the for loop to see what it is findng, and unfortunalty it is only the first account
EDIT: I have included more code here, my after my initial if statement i want to check if the code the user enters is also correct.
see if the name of an employee matches one in the list then the if
statement continues, further questions asked etc... it seems to only
iterate once and then stop as it will only find the first user and
tell me the other accounts do not exisit, even though they do!!
If it works for one employee and tells that others don't exist then your for loop does not iterate once.
The output you get is exactly what the code looks like. You get username once then try to match the same name with every employee in the list. If the names are equal you ask for password, otherwise you print out that employee doesn't exist. Everything right as it is in the code. You should add to your question the expected behaviour so I, or someone else can fix your code without guessing the purpose of your methods.
Here's one of those guesses:
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
boolean userFound = false;
for (Account a : Accounts) {
System.out.println(a);
if (a.getname().equals(empName)) {
System.out.println("\nPlease enter your passcode: ");
String code = Scan.nextLine();
if (a.check(code) == true) {
System.out.println("logged in");
userFound = true;
break;
}
}
}
if(userFound) {
login();
} else {
System.out.println("User not found.");
}
This is a possible solution that doesn't use your Account class (since I do not know what it looks like) and instead uses a Map:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = input.nextLine();
boolean found = false;
Map<String, String> accounts = new HashMap<String, String>();
accounts.put("Geoff", "password1");
accounts.put("Bob", "password2");
accounts.put("John", "password3");
Set<String> names = accounts.keySet();
for (String a : names)
{
if (!a.equals(empName))
{
continue;
}
found = true;
// three tries to login
boolean success = false;
for(int i = 0; i < 3; i++)
{
System.out.println("Please enter your passcode: ");
String code = input.nextLine();
if (accounts.get(a).equals(code))
{
System.out.println("logged in");
success = true;
}
else
{
System.out.println("Wrong password... try again");
}
}
if(!success)
{
System.out.println("User failed to authenticate after 3 attempts. User has been locked out!");
}
}
if(!found)
{
System.out.println("Employee does not exist!");
}
}
Since I do not know what the login() method does, I just simply added that into the code. This solution iterates three times in an attempt to get the correct password. If that fails, a message is displayed.

nullpoint exception. Java. ATM

I am working on an ATM system in java.
And I keep getting NullPointerException error when I execute this code :
Why am I getting this?
The only way for the function to work is, if I create a new user with the admin user. But when I log in without creating new user ( two user are initialised at the start of the program) and try to delete users, the console throws the NullPointerException error.
public void showDeleteUser() {
System.out.println("-----------------------------");
System.out.println("Username of user to delete");
input.nextLine();
String userToDelete = input.nextLine();
User _userToDelete = null;
for (User user : users) {
if (userToDelete.equals(user.getName())) {
_userToDelete = user;
}
}
if (_userToDelete != null) {
users.remove(_userToDelete);
System.out.println("Following user is deleted: " + userToDelete);
} else {
System.out.println("User: " + userToDelete
+ "User could not be found would you like to try again?");
}
}
It could be because input.nextLine(); is never assigned to a variable and thus returns a NullPointer.
You could try: String delete = nextLine(); if you really need it. Because the next line is quite the same String userToDelete = nextLine(); if it is so, then just remove the above mentioned line.

Why won't this method call work?

I'm creating a method to take an input by a user and validate it to make sure it's correct. If it's correct it will call a method and input the user input in to it. But for some reason, the method call is not working. It doesn't produce any errors, it just simply doesn't do it. I placed a print statement at the end of the code to make sure it actually reaches there and it does, but for some reason it's just not calling the method like it's supposed to. The other method works fine if I call it by itself and input a string via the parameters.
The code is:
public void getGetScheduledShowByFilmInput()////new - omar////
{
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
String filmInput;
filmInput = "";
boolean foundFilm;
foundFilm = false;
System.out.println("Here is a list of films that are currently showing:");
for(Film film : films){
System.out.println(film.getFilmName());
}
System.out.println("");
System.out.println("Please type the film name that you wish to view the corresponding shows for and press enter.");
System.out.println("Type 'exit' and press enter to exit this process.");
while(foundFilm == false){
try{
filmInput = reader.readLine();
}
catch (IOException e){
System.out.println("Error");
}
//If user enters "exit" then return.
if(filmInput.equals("exit")){
return;
}
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName() == filmInput){
foundFilm = true;
break;
}
}
if(foundFilm = true){
System.out.println("Film found.");
}
else{
System.out.println("The film name you entered has not been recognised. Please try again.");
}
}
//Call the function and input the film name input by the user.
getScheduledShowsByFilm(filmInput); ////This is the code that seems to be the problem.
System.out.println("reached bottom");
}
and the second method is:
public void getScheduledShowsByFilm(String inputFilmName)
{
ArrayList<Show> scheduledShows;
scheduledShows = new ArrayList<Show>();
for(Film film : films){
if(inputFilmName == film.getFilmName()){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}
for(Show show : scheduledShows){
System.out.println("**********************************");
show.getShowDetails();
System.out.println("**********************************");
}
}
The second method works perfectly when I call it on its own and enter parameters manually though.
It's probably something extremely simple that I'm not understanding! haha, thank you for your help :)
foundFilm can never be false because you always assign true to it:
if(foundFilm = true){
System.out.println("Film found.");
}
try changing it to this:
if(foundFilm)
{
System.out.println("Film found.");
}
In getGetScheduledShowByFilmInput() and getScheduledShowsByFilm(String) avoid doing string comparison using the equality operator (==). The == operator tests for object equality, but you want to test whether two strings contain the same sequence of characters. Therefore, use equals instead:
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName().equals(filmInput)){
foundFilm = true;
break;
}
}
and
for(Film film : films){
if(inputFilmName.equals(film.getFilmName())){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}

Categories

Resources