How make this program terminate after - java

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();
}
}
}
}

Related

How to solve the else/if problems in password input?

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!");

Password checker java program

I am trying to create a program that will check the password of the user. I want the program to end once the user gets it correct but if not I want it to ask only 4 times.
Problem: even if you do get the password correctly the program keeps on asking guess the password. And if you get it wrong it will ask incorrectly. How can I fix this?
import java.util.Scanner;
public class HowToAdd {
public static void main (String [] args){
Scanner input = new Scanner (System.in);
int trys = 0;
String password=null;
do{
System.out.println("Guess the password");
password = input.next();
if(password.equalsIgnoreCase("Password")){
System.out.println("Great job");
}else{
System.out.println("Try again");
input.next();
trys++;
}
}while(trys<2);
System.out.println("Try again later!");
input.close();
}
}
You just need to add a break:
if(password.equalsIgnoreCase("Password")){
System.out.println("Great job");
break;
}
Not only did I add a break to fix the problem of not leaving the loop when correct password is entered but I added a couple of other things to help you out see below:
public static void main (String [] args){
Scanner input = new Scanner (System.in);
int trys = 0;
String password=null;
System.out.println("Guess the password:");
while(trys<2)
{
password = input.next();
if(password.equalsIgnoreCase("Password")){
System.out.println("Great job");
break;
}else{
trys++;
if(trys != 2)
{
System.out.println("Try again:");
}
}
}
if(trys == 2)
{
System.out.println("Try again later!");
}
input.close();
}
Try this it will break out of the loop if it is correct using the break; statement. Also it will only display guess a password the first try then try again after that. Also it won't say try again later if they guessed right because it checks if they guessed wrong twice.
You can fix it with a break keyword, like so :
if(password.equalsIgnoreCase("Password")){
System.out.println("Great job");
break;
}
The break is explained here :
Branching Statements
What you need to implement can be done without using break statements.
Try to look at the flow of my codes.
Scanner scn = new Scanner(System.in);
int tries=0;
String pw = "";
System.out.println("Guess the password");
pw = scn.nextLine();
while(!pw.equalsIgnoreCase("Password") && tries < 3){
tries++;
System.out.println("Try again");
pw = scn.nextLine();
}
if(tries >= 3)
System.out.println("Try again later!");
else
System.out.println("Great job!");
TEST RUN 1:
Guess the password
1st try
Try again
2nd try
Try again
3rd try
Try again
last try
Try again later!
TEST RUN 2:
Guess the password
password
Great job!
Here is another variant of code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int trys = 0;
String password = null;
// create variable for a number of tries
int numberOfCheks = 4;
do {
System.out.println("Guess the password");
password = input.nextLine();
if (password.equalsIgnoreCase("Password")) {
System.out.println("Great job");
break;
} else if (++trys == numberOfCheks) {
//Break if you've used all your tries
System.out.println("Try again later!");
break;
} else {
System.out.println("Try again");
// input.next(); - Useless. You don't handle it. Removed
}
//There is already tries number check. So 'true' can be used as the condition.
} while (true);
input.close();
}

I keep getting an "else without if" error

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
}
}

Java Basic Login Feature

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

Read in yes/no boolean from terminal and produce an if else with inputted value

I asked a user if they would like to play a game..
System.out.println("Would you like to play");
read in yes or no value
if yes (display text)
else (display other text)
I have used the scanner previously in the program, I just need it to use it again. Do I need to declare another new one with new variables?
you could do something like:
String yesOrNo = System.in.readLine();
String textToDisplay = (yesOrNo.equals("Yes")) ? "text to display when yesOrNo equals yes" : "text to display when YesOrNo equals no";
Use this method:
scanner.nextBoolean()
So then it'd be:
System.out.println("Would you like to play?");
Scanner scanner = new Scanner(System.in);
if(scanner.nextBoolean()==true) {
System.out.println("This will be fun");
} else {
System.out.println("Maybe next time");
}
Edit
System.out.println("Would you like to play?");
Scanner scanner = new Scanner(System.in);
String val = scanner.next();
if(val.equalsIgnoreCase("y")||val.equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if(val.equalsIgnoreCase("n")||val.equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
To make it simple, here is something for you to play with:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
System.out.println("Would you like to play: 'y' or 'yes' to accept; 'n' or 'no' to reject; 'q' to quit:");
Scanner scanner = new Scanner(System.in);
String token = "";
while(scanner.hasNextLine())
{
token = scanner.nextLine().trim();
if(token.equalsIgnoreCase("q")) System.exit(0);
if(token.equalsIgnoreCase("y")||token.equalsIgnoreCase("yes"))
{
System.out.println("Thanks for your interest!");
System.exit(0);
}
else if (token.equalsIgnoreCase("n")||token.equalsIgnoreCase("no"))
{
System.out.println("That's a pity!");
System.exit(0);
}
else
{
System.out.println("Oops, not a valid input!");
}
}
}
}
I just stumbled upon this question and the answer of Chad M is correct, but - like some commenters mentioned above - has some bugs in it. So here is my implementation without the bugs (it was just a question of saving the user input into a string variable):
Scanner scanner = new Scanner(System.in);
String userInput = scanner.next();
if(userInput.equalsIgnoreCase("y") || userInput.equalsIgnoreCase("yes")) {
// y or yes
} else {
// other character
}
Based on a recommendation of dragon66, I'm implementing a String comparison of predefined inputs compared to user input.
System.out.println("Would you like to play? Or press Q to exit"):
Scanner scanner = new Scanner(System.in);
String affirmative = "yes";
String affirmative2 = "y";
String negative = "no";
String negative2 = "n";
String quit = "q";
if(scanner.next().equalsIgnoreCase(affirmative)||scanner.next().equalsIgnoreCase(affirmative2)) {
System.out.println("This will be fun");
} else if(scanner.next().equalsIgnoreCase(negative)||scanner.next().equalsIgnoreCase(negative2)) {
System.out.println("Maybe next time");
} else if(scanner.next().equalsIgnoreCase(quit)){
System.out.println("Good bye");
System.exit();
} else {
System.out.println("Invalid character");
}

Categories