I wrote a program that users can login. Below u see some codes that I wrote for the password input but the second if of them does not work properly.
Please help me to find the problem. Why it does not work?
import java.util.Scanner;
public class Password {
public static void main(String[] args) {
Scanner passwordInput = new Scanner(System.in);
System.out.print("Please enter your password: ");
int builtInPassword = 1254;
if (passwordInput.hasNextInt() && passwordInput.nextInt() == builtInPassword) {
System.out.println("Your password is correct.");
} else if (passwordInput.hasNextInt() && passwordInput.nextInt() != builtInPassword) {
System.out.println("The password entered is incorrect");
} else {
System.out.println("Sorry, please enter the right format");
}
}
}
The problem is that you call nextInt() in all ifs. This way you basically wait for another input each time you call passwordInput.nextInt().
Try to save the user input and then check it for the password. Something like:
if (passwordInput.hasNextInt()) {
int pass = passwordInput.nextInt();
if (pass == builtInPassword) {
System.out.println("Your password is correct.");
} else {
System.out.println("The password entered is incorrect");
}
} else {
System.out.println("Sorry, please enter the right format");
}
I am writing without a compiler here so I am not sure it will compile properly but you can get the idea ;)
scanner.hasNextInt() check the value is int or not, but its not consume the value. but in your code "pasword not matching" case scanner will go through two ifs and two hasNextInt() callings. therefore in second if it will return false value.
you can correct and optimize you code using exceptions as follow.
try {
if(passwordInput.nextInt()==builtInPassword){
System.out.println("Your password is correct.");
}else{
System.out.println("The password entered is incorrect");
}
} catch (InputMismatchException e) {
System.out.println("Sorry, please enter the right format");
}
As noted by others, the problem is that you are calling nextInt() twice, and it tries to get a new int each time. The simplest solution would be to change your first else to else if (passwordInput.hasNextInt()) {, as you already know the second condition (the password is wrong) holds from the fact that the if failed. However, I would advise restructuring your code so that there is no need to call hasNextInt twice either, as this seems cleaner:
if (passwordInput.hasNextInt()) {
if (passwordInput.nextInt() == builtInPassword) {
System.out.println("Your password is correct.");
} else {
System.out.println("The password entered is incorrect.");
}
} else {
System.out.println("Sorry, please enter the right format");
}
I you need a while loop.
while (passwordInput.nextInt() != builtInPassword) {
System.out.println("Incorrect password");
}
System.out.println("Correct password!");
Related
package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("What is the password?");
Scanner new2 = new Scanner(System.in);
int input = 0;
while(input <= 5 )
{
String password = new2.nextLine();
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
else if("bluesky123".equals(password)) {
System.out.println("You got it right!");
break;
}
else if(input == 5) {
System.out.println("maximum number of attempts reached");
break;
}
}
}
}
basically, once I hit the 5 loops, it just says "incorrect password" and breaks. not the "maximum attempts" message.
Allow me to annotate:
This if statement will always be evaluated:
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
This if statement will only be evaluated if the password is "bluesky123". In this case, it will always evaluate to true.
else if("bluesky123".equals(password)) {
System.out.println("You got it right!");
break;
}
There is no case when this if statement will ever be evaluated. Once if-else finds a statement that is true, it will skip all others in that section.
else if(input == 5) {
System.out.println("maximum number of attempts reached");
break;
}
In your case, you should consider a nested if (i.e. an if inside another if).
while(input <= 5 )
{
String password = new2.nextLine();
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
else {
System.out.println("You got it right!");
break;
}
if((input == 5) && (!password.equals("bluesky123"))) {
System.out.println("maximum number of attempts reached");
break;
}
}
Your logic has some flaws. You have to pay attention to how JAVA processes if / else if
https://www.tutorialspoint.com/java/if_else_statement_in_java.htm
I tested your code it is working! The only thing that you need to do is to move the follow line to inside the while loop
System.out.println("What is the password?");
Doing this it will print "Incorrect password" and then it will print again
"What is the password?"
Because in the way that it is working now seems that the software is not waiting the password to be retyped when in fact it is.
I'm doing a java program for an assignment, and one of the exceptions are that the user cannot input a value for a row or column that does not exist. i.e If the board was 5x7 and the user entered a column of value 10 the screen would print "Error: Invalid column" . However i'm unsure how to do this final exception and i need to submit it today. If anyone could help i'd really appreciate it! Here is my code for the makeGuess() function:
public void makeGuess(){
//guesses is for keeping track of your guesses
boolean cont=true;
int rowGuess;
int columnGuess;
do{
System.out.println("Enter a row to guess >");
rowGuess = (input.nextInt()-1);
if(rowGuess<=0){
System.out.println("You did not enter a positive Integer.Please try again");
cont=false;}
else{
cont=true;}
}
while (cont==false);
do{
System.out.println("Enter a column to guess >");
columnGuess = (input.nextInt()-1);
if(columnGuess <=0){
System.out.println("You did not enter a positive integer.Please try again");
cont=false;
} else{
cont=true;
}
}while(cont==false);
Assuming that the rest of your code works, you could simply alter your if statements to ensure the entry is valid.
Using the OR operator ||:
if (columnGuess <= 0 || columnGuess >= 10){
System.out.println("Error: invalid Column");
}
just as you have an if statement to test if the number is too small you also need to test if it is too big
public void makeGuess(){
//guesses is for keeping track of your guesses
boolean cont=true;
int rowGuess;
int columnGuess;
do{
System.out.println("Enter a row to guess >");
rowGuess = (input.nextInt()-1);
if(rowGuess<=0){
System.out.println("You did not enter a positive Integer.Please try again");
cont=false;
}else if(rowGuess>7){
System.out.println("You did not enter a small enough Integer.Please try again");
cont=false;
}else{
cont=true;
}
}while (cont==false);
do{
System.out.println("Enter a column to guess >");
columnGuess = (input.nextInt()-1);
if(columnGuess <=0){
System.out.println("You did not enter a positive integer.Pleasetry again");
cont=false;
}else if(columnGuess>5){
System.out.println("You did not enter a small enough Integer.Please try again");
cont=false;
} else{
cont=true;
}
}while(cont==false);
A better way to do this in my experience is to create your own exception
public class BadMoveException extends Exception {
BadMoveException(Exception ex) {
super(ex);
}
BadMoveException(String ex) {
super(ex);
}
}
Make makeGuess throw BadMoveException, and then for any of the invalid moves the user can make, you can create a BadMoveException with that, and print it in the catch { } block outside of makeGuess
while (!gameOver) {
try {
makeGuess();
}
catch (BadMoveException ex) {
System.out.println("You tried to make an invalid move:" + ex.getMessage());
}
}
I'm trying to write some code that makes the user input a valid username and they get three tries to do it. Every time I compile it I get an else without if error wherever I have a else if statement.
Scanner in = new Scanner(System.in);
String validName = "thomsondw";
System.out.print("Please enter a valid username: ");
String input1 = in.next();
if (input1.equals(validName))
{
System.out.println("Ok you made it through username check");
}
else
{
String input2 = in.next();
}
else if (input2.equals(validName))
{
System.out.println("Ok you made it through username check");
}
else
{
String input3 = in.next();
}
else if (input3.equals(validName))
{
System.out.println("Ok you made it through username check");
}
else
{
return;
}
You are misunderstanding the use of if-else
if(condition){
//condition is true here
}else{
//otherwise
}else if{
// error cause it could never be reach this condition
}
Read more The if-then and if-then-else Statements
You can have
if(condition){
}else if (anotherCondition){
}else{
//otherwise means 'condition' is false and 'anotherCondition' is false too
}
If you have an if followed by an else, that ends the block. You can have if followed by multiple else if statements, but only one else -- and the else must be last.
You need to either: change all your "else" except the last to "else if", or put plain "if" before the following "else if" statements:
(1)
else if (input2.equals(validName))
{
System.out.println("Ok you made it through username check");
}
(2)
else if (input3.equals(validName))
{
System.out.println("Ok you made it through username check");
}
Your code is not very maintainable. What would you do, if the user got 5 tries? Add some additional if blocks? And what if the user has 10 tries? :-) You see what I mean.
Try the following instead:
Scanner in = new Scanner(System.in);
int tries = 0;
int maxTries = 3;
String validName = "thomsondw";
while (tries < maxTries) {
tries++;
System.out.print("Please enter a valid username: ");
String input = in.next();
if (input.equals(validName)) {
System.out.println("Ok you made it through username check");
break; //leaves the while block
}
}
Below is a simple program that I wrote that will ask for a password. If I enter the incorrect password I am prompted with "Password incorrect would you like to try again?", and if I say no or anything else that doesn't begin with a 'y', it will terminate the program. The problem is, if I enter the correct password which is "Noah" it says "Password correct" and it loops back to "Enter password" again. How can I make this program terminate after I enter the correct password? Thank you.
import java.util.Scanner;
public class methods
{
public static void main (String [] args)
{
Scanner sc = new Scanner(System.in);
String response = "yes";
System.out.println("Enter password:");
while(response.charAt(0)=='y')
{
String input = sc.nextLine();
if(input.equalsIgnoreCase("Noah")==true)
{
System.out.println("Password correct");
}
else if(input.equalsIgnoreCase("Noah")==false)
{
System.out.println("Password incorrect, would you like to try again?");
response = sc.nextLine();
}
}
}
}
while(response.charAt(0)=='y')
{ System.out.println("Enter password")
String input = sc.nextLine();
if(input.equalsIgnoreCase("Noah")==true)
{
System.out.println("Password correct");
break;
}
else if(input.equalsIgnoreCase("Noah")==false)
{
System.out.println("Password incorrect, would you like to try again?");
response = sc.nextLine();
}
}
use break; then you can terminate.
if("Noah".equalsIgnoreCase(input)){
System.out.println("Password correct");
break;
}
There are a few ways. In increasing severity:
1) Use a break statement. That will take program control flow to just after the end of the while loop.
2) Use a return statement. That will exit the function and, in your specific case, that will end the program.
3) Insert System.exit(n) where n is a number, probably non-zero, to indicate a return status. This terminates the Java Virtual Machine, and returns the value n to the operating system.
In your case I'd be inclined to go with (1) or (2).
if(input.equalsIgnoreCase("Noah")==true)
{
System.out.println("Password correct");
break;
}
or you can add response ="no";
if(input.equalsIgnoreCase("Noah")==true)
{
System.out.println("Password correct");
response ="no";
}
" no" or anything that dose not start with the 'y' char .
After doing a couple of changes, I guess this is what you are looking for :
import java.util.Scanner;
public class Methods{
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
String response = "yes";
while(response.charAt(0)=='y'){
System.out.println("Enter password:");
String input = sc.nextLine();
if(input.equalsIgnoreCase("Noah")==true){
System.out.println("Password correct");
break;
}
else if(input.equalsIgnoreCase("Noah")==false){
System.out.println("Password incorrect, would you like to try again?");
response = sc.nextLine();
}
}
}
}
I'm trying to implement a login feature in this program. I finally figured it out how to do a basic one, but sadly I do not know how to end it, like for example if the user had finally reached the limit of 3 it should end, but mine still continues and I don't know where and what code I should put in order for it to end than continuing to the main program.
import java.io.*;
public class Password{
public static void main(String args[]) throws IOException{
String name, un, pw;
String Username = "passwordtest";
String Password = "test123";
int stud;
double math, science, english, filipino, social, ave, sum, fingrade;
BufferedReader inpt = new BufferedReader (new InputStreamReader(System.in));
for(int trial=1; trial<=3; trial++){
System.out.print("Username: ");
un = inpt.readLine();
System.out.print("Password: ");
pw = inpt.readLine();
System.out.println("");
if (un.equals(Username) && pw.equals(Password)){
System.out.println("You have successfully logged in!");
trial=trial+2;
continue;
}else{
System.out.println("Sorry, Incorrect Username/Password");
System.out.println("Please Try Again");
System.out.println("");
}
}
System.out.println("");
System.out.println("Welcome to ITMinions' Grading System!");
System.out.println("How many students' grades would you like to record?");
System.out.print("Answer: ");
stud=Integer.parseInt(inpt.readLine());
System.out.println("");
for (int ctr=1; ctr<=stud; ctr++){
System.out.print("Name of the student: ");
name = inpt.readLine();
System.out.println("");
System.out.println("Input the following grades");
System.out.print("Math: ");
math = Double.parseDouble(inpt.readLine());
if(math<65 || math>100){
System.out.println("");
System.out.println("Wrong input, try again.");
System.out.println("");
ctr=ctr-1;
continue;
}
System.out.print("Science: ");
science = Double.parseDouble(inpt.readLine());
if(science<65 || science>100){
System.out.println("");
System.out.println("Wrong input, try again.");
System.out.println("");
ctr=ctr-1;
continue;
}
System.out.print("English: ");
english = Double.parseDouble(inpt.readLine());
if(english<65 || english>100){
System.out.println("");
System.out.println("Wrong input, try again.");
System.out.println("");
ctr=ctr-1;
continue;
}
System.out.print("Filipino: ");
filipino = Double.parseDouble(inpt.readLine());
if(filipino<65 || filipino>100){
System.out.println("");
System.out.println("Wrong input, try again.");
System.out.println("");
ctr=ctr-1;
continue;
}
System.out.print("History: ");
social = Double.parseDouble(inpt.readLine());
if(social<65 || social>100){
System.out.println("");
System.out.println("Wrong input, try again.");
System.out.println("");
ctr=ctr-1;
continue;
}
sum=math+science+english+filipino+social;
ave=sum/5;
System.out.println("");
System.out.println("The average of " + name + " is: " + ave);
System.out.println("");
}
}
}
Please help! And yes this is related to school work :)
Thanks!
I would rewrite the part of the loop that handles succesfull login as follows:
if (un.equals(Username) && pw.equals(Password)){
System.out.println("You have successfully logged in!");
break;
}
Notice using the break keyword to break out of the loop.
You can use System.exit(0); to exit when the user has used all login attempts.
You must use another variable for example: boolean isLoggedIn, and set that if successfully logged in, and then break instead of continue as below:
if (un.equals(Username) && pw.equals(Password)){
System.out.println("You have successfully logged in!");
isLoggedIn = true;
break;
}else{
System.out.println("Sorry, Incorrect Username/Password");
System.out.println("Please Try Again");
System.out.println("");
}
Then outside the for loop, check if(isLoggedIn) and do actions accordingly.
Modify your fi statement
if (un.equals(Username) && pw.equals(Password)){
System.out.println("You have successfully logged in!");
break;;
}else{
System.out.println("Sorry, Incorrect Username/Password");
System.out.println("Please Try Again");
System.out.println("");
}
}
if(trail==4)
{
//Write your locking logic here
}
its not good practice to hard code things in your code. Try to use property file for simplicity or if you have time use jdbc
To avoid Null pointer exception use
Username.equals(un)
Also, make sure you follow proper Java coding standards like camel-case for variable naming, and all upper case for constants. Since username and password are hardcoded, they are infact constants. So, change
String Username = "passwordtest";
String Password = "test123";
to
final String USERNAME = "passwordtest";
final String PASSWORD = "test123";
It would also be better if you could load these constants from a properties file, because when passwords change, you need not modify your code, just edit properties file.
To clarify the previous answers:
booelan isLoggedIn = false;
for ( int trials = 3; trials > 0; trials-- )
{
<ask uname, password> // Java convention: don't capitalise variable names
if ( isLoggedIn = <uname/password are OK> {
System.out.println ( "Success" );
break;
}
System.out.printf ( "Bad uname/pass, %d attempts remaining\n", trials );
}
if ( !isLoggedIn ) {
System.out.println ( "User couldn't give valid credentials, quitting after three attempts, due to security reasons" );
Thread.sleep ( 3000 ) // try to fight brute-force attackers
System.exit ( 1 ); // Not zero, it's not a regular end
}
// Go ahead with your application