Is there a way to make an "if" inside another if" - java

How do I make it so that if the username is incorrect, it doesn't ask for the password but immediately says that the username is incorrect?
import java.util.Scanner;
public class SecurityPasscode
{
public static void main(String[] args)
{
Scanner user_input = new Scanner(System. in );
System.out.println("Enter Username");
String username;
username = user_input.next();
if (username.equals("username"))
System.out.println("Enter Password");
String password;
password = user_input.next();
if (password.equals("password"))
System.out.println("Welcome back " + username + "!");
if (!"password".equals(password))
System.out.println("That password is incorrect.");
else if (!"username".equals(username))
System.out.println("That username is incorrect.");
}
}

Add { after your first if....
Note that these two blocks of code are not the same:
if(something1)
command1;
command2;
if(something2)
command3;
else if(something3)
if(something1) {
command1;
command2;
if(something2)
command3;
}
else if(something3)
In the first code, the else corresponds to the last if. In the second code, it corresponds to the first if. Furthermore, in the first code, command2 is not in the scope of the external if because Java doesn't really cares about indentation..

if (username.equals("username")){
System.out.println("Enter Password");
}else{
String password;
password = user_input.next();
if (password.equals("password")){
System.out.println("Welcome back " + username + "!");
}else{
System.out.println("That password is incorrect.");
}
}

if (condition)
{
if (another condition)
{
// statements here
}
}

yes...
if(eval)
if(anotherEval)
....
code
you could have any number of nested if as you like :)

Related

Method keeps returning an if-statement even though the conditions are not meet

I spent a few hours on this assignment already but the gist of it is to write up a code that will ask a user for a username & password and 'create' an account for them. There are certain requirements for the username and password and they are as so:
Username must not start with a letter.
Username must contain at least 6 characters and no more than 12 characters.
Password must not contain the username.
Password must be at least 8 characters long and no more than 16 characters.
if (password.contains(username)) {
System.out.println("password cannot contain the username");
It will return the other messages if the inputted password is <8 or >16 characters but this line always gets returned for some reason. I've input a password that contains no characters from the username and it will still return it. I'm in a bit of a pickle and require assistance. I don't understand what I am doing wrong either. In plain English, that line should do expect what I need it to: Check to see if password contains username!!
TIA
import java.util.Scanner;
public class Module2 {
Scanner reader = new Scanner(System.in);
String username;
String password;
public Module2() {
this.username = "";
this.password = "";
}
public static void main(String[] args) {
System.out.println("starting application: initiating username and password creation");
Module2 m2 = new Module2();
m2.getUsername();
}
public String getUsername() {
Scanner reader = new Scanner(System.in);
System.out.println("new username: must start with a letter and be at least 6 characters
long but not more than 12 characters");
//grabs input, store into String input
String input = reader.next();
char a = input.charAt(0);
boolean v = Character.isLetter(a);
//this entire statement will print the appropriate error messages
if (!v) {
System.out.println("username must begin with a letter");
} else if (input.length() < 6) {
System.out.println("username must be at least 6 characters long");
} else if (input.length() > 12) {
System.out.println("username must not be longer than 12 characters");
} else {
System.out.println("Thank you " + input);
getPassword();
}
return "";
}
public String getPassword() {
Scanner scanner = new Scanner(System.in);
System.out.println("new password: must be at least 8 characters long but no more than 16
characters long and cannot contain the username");
String password = scanner.nextLine();
if (password.contains(username)) {
System.out.println("password cannot contain the username");
} else if (password.length() < 8) {
System.out.println("password has to be at least 8 characters long");
} else if (password.length() > 16) {
System.out.println("password must not contain more than 16 characters");
} else {
System.out.println("Thank you\n" + password);
System.out.println("username and password validated");
System.out.println("ending application");
}
return "";
}
}

How do you get a certain block of code (in Java) to keep repeating until the user chooses to exit? [duplicate]

This question already has answers here:
How do I loop until the user makes correct input on Java?
(4 answers)
Closed 2 years ago.
For example, in the code below, how do I make it such that I can keep running the "enter username" part until the user chooses to exit?
import java.util.Scanner;
public class EnterUserName {
public static void main(String[] args) {
Scanner user1 = new Scanner(System.in);
System.out.println("Enter your username: ");
String userName = user1.nextLine();
System.out.println("Username: " + userName);
}
}
How should the user indicate they would like to exit? If they just end the process themselves, you don't need to do anything, just put it inside a while loop like so:
public class EnterUserName {
public static void main(String[] args) {
Scanner user1 = new Scanner(System.in);
String userName;
while (true) { //loop forever
System.out.println("Enter your username: ");
userName = user1.nextLine();
System.out.println("Username: " + userName);
}
}
}
Another option is to just have them enter a special keyword, maybe something like "exit". This could be implemented like so:
public class EnterUserName {
public static void main(String[] args) {
Scanner user1 = new Scanner(System.in);
String userName;
while (true) { //loop forever
System.out.println("Enter your username: ");
userName = user1.nextLine();
if (userName.equals("exit")) { //if the user entered "exit"
break; //break out of the loop (terminates the program in this case)
}
System.out.println("Username: " + userName);
}
}
}
New to code can be hard.
You can use break in a loop (for loop, while loop, do while loop) if you wish your progarm continue the remaining code, or you can use System.exit(0) to immediately stop the program.
I am assuming that you do not need validation. If you need it just change else to else if (expression) in the code expamle
I am also want you to fix the way you naming variables, you should name it like the example for the clarification. And you should declare variables out of a loop String userName;, it is a good practice. Here is the code example:
public class EnterUserName {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userName;
while (true) { // Loop forever until correct input or choose "1"
System.out.println("Enter your username or enter 1 to exit: ");
userName = input.nextLine();
if (userName.equals("1")) {
System.exit(0); // immediately stop the program
// Or you can use break too. If you use break, "End program" will be printed;
// break;
} else { // You can use else if here to have validation of Username
System.out.println("You have enter Username: " + userName);
break; // Correct input, break out the loop
}
}
System.out.println("End program");
}
}

User validation testing in Java while loop

I am making one of my first java projects checking if a user input word (no numbers or symbols) is a palindrome. I used the method outlined here: https://stackoverflow.com/a/4139065/10421526 for the logic. The code works per-request but I am having trouble re-prompting the user after invalid input as it seems to "block" the ability of my code to accept valid input, printing my "retry" message. I have also tried the do while version but I ended up with formatting errors. I think the way I define my stringOut variable is giving me trouble but Im not sure how to change that without making a duplicate as eclipse says. Here is the closest I could get after dozens of tries going in circles:
import java.util.Scanner;
public class PalindromTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("Input word to test: ");
String stringIn = in.nextLine();
String stringOut = new StringBuilder(stringIn).reverse().toString();
while (!stringIn.matches("[a-zA-Z]+")) {
System.out.println("Invalid input, try again.");
in.next(); //stops infinite error loop
}
if ((stringIn.equalsIgnoreCase(stringOut))) {
System.out.println("Palindrome detected");
System.out.println("You entered: " + stringIn);
System.out.println("Your string reversed is: " + stringOut);
} else {
System.out.println("Not a palindrome");
}
}
}
change in.next(); in while loop to stringIn= in.next(); and after while loop add stringOut = new StringBuilder(stringIn).reverse().toString(); .
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("Input word to test: ");
String stringIn = in.nextLine();
String stringOut = new StringBuilder(stringIn).reverse().toString();
while (!stringIn.matches("[a-zA-Z]+")) {
System.out.println("Invalid input, try again.");
stringIn= in.next(); //stops infinite error loop
}
stringOut = new StringBuilder(stringIn).reverse().toString();
if ((stringIn.equalsIgnoreCase(stringOut))) {
System.out.println("Palindrome detected");
System.out.println("You entered: " + stringIn);
System.out.println("Your string reversed is: " + stringOut);
} else {
System.out.println("Not a palindrome");
}
}
}
A very good use-case to use do-while loop. You use this loop when you have to make sure that your statements are executed at least once. And the subsequent execution is executed only if it matches a condition. In this case, that condition would be validating your input.
Scanner in = new Scanner(System.in);
String prompt = "Input word to test: ";
String stringIn;
do {
System.out.println(prompt);
stringIn = in.nextLine();
prompt = "Invalid input, try again.";
}
while (stringIn.matches("[a-zA-Z]+"));
If the input is non-numeric the while condition would be true and will make this loop run again, hence asking for new input. if the input is numeric the while condition will be false hence exit the while loop and will give you user input in stringIn variable.

Java code not running as planned

This isn't the entire code, just the problem area. (Full code below)
if (passLength > 4) {
System.out.println("Signup alost complete.");
Random rand = new Random();
int randm = rand.nextInt(100000) + 1;
System.out.println(
"To confirm you are not a robot, please enter this code: "
+ randm);
String code = userInput.next();
if (code.equals(randm)) {
System.out.println("Thank you, " + userName);
System.out.println(
"You may now login. Begin by entering your username");
if (userInput.equals(userName)) {
System.out.println("Now please enter you password");
}
// Where the rest of the program will go
}
else {
System.out.println("The code entered is incorrect.");
}
}
else {
System.out.println("Invalid Password");
}
I am making a program where the user makes an account, then later signs in. The part I am having trouble with is a verification to ensure the user is human (they obviously are, but still). After creating their username and password, I generate and print a random int, and they have to type it back.
My problem is that the program always skips to the else statement, and prints "The code entered is incorrect." Even when I enter it perfectly.
Can anyone tell me what I'm doing wrong?
Below is the entire code, just in case.
public static void main(String[] args) {
System.out.println("Hi! To begin please choose your username.");
System.out.println("To do this, please enter your username below. ");
System.out.println("This name must be at least three characters.");
Scanner userInput = new Scanner(System.in);
String userName = userInput.next();
int nameLength = userName.length();
if (nameLength > 2) {
System.out.println("Now please enter your password.");
System.out
.println("This password must be at lease five characters");
String passWord = userInput.next();
int passLength = passWord.length();
if (passLength > 4) {
System.out.println("Signup alost complete.");
Random rand = new Random();
int randm = rand.nextInt(100000) + 1;
System.out.println(
"To confirm you are not a robot, please enter this code: "
+ randm);
String code = userInput.next();
if (code.equals(randm)) {
System.out.println("Thank you, " + userName);
System.out.println(
"You may now login. Begin by entering your username");
if (userInput.equals(userName)) {
System.out.println("Now please enter you password");
}
// Where the rest of the program will go
}
else {
System.out.println("The code entered is incorrect.");
}
}
else {
System.out.println("Invalid Password");
}
}
else {
System.out.println("Invalid Username");
}
}
You are comparing a String with an integer, which can't be the same obviously.
int randm = rand.nextInt(100000) + 1;
...
String code = userInput.next();
if (code.equals(randm))
To solve the problem you could convert the integer to a String and compare the strings (or the other way).
String randm = String.valueOfrand.nextInt(100000) + 1;
...
String code = userInput.next();
if (code.equals(randm)) // Comparing string now
Edit : As #Pshemo pointed out, int code = userInput.nextInt(); will do the work given that you compare the integers with ==.
It's because randm is int and code is String. So the code if (code.equals(randm)) always results to false.
You cannot compare a string and an integer.
Trying taking the input as an integer instead of a String.
String code = userInput.next();
Instead use:
int code= userInput.nextInt();
if(code==randm)
Or you could convert the integer to a String as well

Code doesn't continue after the do-while loop?

I have began to learn Java in my AS level computing class, and have really taken to the first DIY task we have been set.
I have used a do-while statement to see if the input username from the user is in the array "names"- if it's not, it requests to re-enter the username, until a correct one is inserted. I have also set up a boolean, so when a correct username is entered, it cancels the do-while loop and continues with code - but it doesn't.
String[] names = {"mckeownl", "heardj", "williamsc"};
String[] attendance = {"yes", "no", "yes"};
int[] grade = {96, 66, 73};
boolean loggedin = false;
Scanner user_input = new Scanner(System.in);
String login;
login = user_input.next();
do { // beginning of while - login
System.out.println("Insert student's surname followed by the first letter");
System.out.print("of their first name (e.g John Smith = smithj): ");
if (Arrays.asList(names).contains(login)) {
System.out.println("Student selected: "+login+".");
loggedin = true;
}
else {
System.out.println("Incorrect student name! Please try again.");
loggedin = false;
}
} while ( ! loggedin);
if (login.equals(names[0])) {
System.out.println("Attend today: "+attendance[0]);
System.out.println("Grade: ");
}
else {
System.out.println("poo");
}
}
}
The output for a correct name is ;
"Insert student's surname followed by the first letter
of their first name (e.g John Smith = smithj): mckeownl
Student selected: mckeownl."
Why isn't the final if statement output?
You should be asking for the login inside the loop.
You shouldn't set the loggedin variable to false if it fails. Just give text that it failed, then it'll return to the top and ask for login again.
You can have multiple lines in a method call. So you could have:
System.out.println("Insert student's surname followed by the first letter " +
"of their first name (e.g John Smith = smithj): ");
Instead of:
System.out.println("Insert student's surname followed by the first letter");
System.out.print("of their first name (e.g John Smith = smithj): ");
put login = user_input.next(); inside the loop.. In order for the user to loggedin again..
do { // beginning of while - login
System.out.println("Insert student's surname followed by the first letter");
System.out.print("of their first name (e.g John Smith = smithj): ")
login = user_input.next(); // <--- you should ask for login here
...
updated:
//for the final if statement
if (loggedin) { //just use this boolean variable since you used it as an indicator if it is valid name or not
System.out.println("Attend today: "+attendance[0]);
System.out.println("Grade: ");
}
else {
System.out.println("poo");
}
actually, you don't need to put condition after the loop since you already filter it inside the loop so if the name is not valid it will not exit the loop until the user enter a valid name.. you can just do it like this after the loop
do{
..
}while(..)
System.out.println("Attend today: "+attendance[0]);
System.out.println("Grade: ");
I started from scratch, and have created this, which uses the same principles, but has solved my answer.
There are three users, each with their own login, password creation and password entry (if you have a better way to do this, please say).
package codeyom9a;
import java.util.Scanner;
public class Codeyom9a {
public static void main(String[] args) {
String[] names = {"Luke", "Jack", "Brad" };
String[] surnames = {"Mckeown", "Heard", "Reed" };
Scanner user_input = new Scanner(System.in);
boolean firstloggedin;
boolean passloggedin;
String firstlogin;
do { //login first name
firstloggedin = false;
System.out.print("Enter your first name: ");
firstlogin = user_input.next();
if (firstlogin.equals(names[0]) || firstlogin.equals(names[1]) || firstlogin.equals(names[2])) {
firstloggedin = true;
}
else {
System.out.println("Please try again.");
}
} while (! firstloggedin);
boolean secondloggedin;
String secondlogin;
do { //login surname
secondloggedin = false;
System.out.print("Enter your surname: ");
secondlogin = user_input.next();
if (secondlogin.equals(surnames[0]) & firstlogin.equals(names[0])|| secondlogin.equals(surnames[1]) & firstlogin.equals(names[1]) || secondlogin.equals(surnames[2]) & firstlogin.equals(names[2])) {
secondloggedin = true;
}
else {
System.out.println("Please try again.");
}
} while (! secondloggedin);
if (secondlogin.equals(surnames[0]) & firstlogin.equals(names[0])) { //pass login user 1
String password1; //pass create user 1
System.out.print("Create a password (no spaces): ");
password1 = user_input.next();
boolean passloggedin1 = false;
do{
String passwordenter1; //pass enter user 1
System.out.print("Enter your password now: ");
passwordenter1 = user_input.next();
if (passwordenter1.equals(password1)) {
passloggedin1 = true;
System.out.println("Correct! You have now logged in.");
}
else {
System.out.println("Incorrect password!");
}
} while (! passloggedin1);
} //end user 1
if (secondlogin.equals(surnames[1]) & firstlogin.equals(names[1])) { //pass login user 2
String password2; //pass create user 2
System.out.print("Create a password (no spaces): ");
password2 = user_input.next();
boolean passloggedin2 = false;
do{
String passwordenter2; //pass enter user 2
System.out.print("Enter your password now: ");
passwordenter2 = user_input.next();
if (passwordenter2.equals(password2)) {
passloggedin2 = true;
System.out.println("Correct! You have now logged in.");
}
else {
System.out.println("Incorrect password!");
}
} while (! passloggedin2);
} //end user 2
if (secondlogin.equals(surnames[2]) & firstlogin.equals(names[2])) { //pass login user 3
String password3; //pass create user 3
System.out.print("Create a password (no spaces): ");
password3 = user_input.next();
boolean passloggedin3 = false;
do{
String passwordenter3; //pass enter user 3
System.out.print("Enter your password now: ");
passwordenter3 = user_input.next();
if (passwordenter3.equals(password3)) {
passloggedin3 = true;
System.out.println("Correct! You have now logged in.");
}
else {
System.out.println("Incorrect password!");
}
} while (! passloggedin3);
} //end user 3
}
}
If you type in "Luke", "Jack", or "Brad", it then requests for the surname (which is in the same index in the 'surnames' array). If both correct, it request for a password to be created, and then asks for the user to input that created password.
Regarding my first code, I don't know why this works and the other doesn't, any ideas why?

Categories