I'm practicing if and else statements and i did a guess your password string, if you input the right password a congratulation message appears but if you enter the wrong one another message appears that says "Please try again" the issue that im having is that i dont know how to set another congratulation message if the user guess the right password on try again.
public static void main(String[] args) {
String password = "Shippuden345";
System.out.println("Enter or guess the password: ");
Scanner scanner = new Scanner(System.in);
String guess = scanner.nextLine();
System.out.println(password.equals(guess));
if (password.equals(guess)) {
System.out.println("Your guess was correct");
return;
}
else;
{
System.out.println("Please try again: ");
Scanner scanner1 = new Scanner(System.in);
String again = scanner1.nextLine();
}
}
}
i want to set another message in here, if the user guess the password correctly after trying again.
else;
{
System.out.println("Please try again: ");
Scanner scanner1 = new Scanner(System.in);
String again = scanner1.nextLine();
}
}
}
It would be best if you used a do while loop:
public static void main(String[] args) {
String password = "Shippuden345";
String guess;
do{
System.out.println("Enter or guess the password: ");
guess = scanner.nextLine();
System.out.println(password.equals(guess));
if (password.equals(guess)) {
System.out.println("Your guess was correct");
return;
}
else {
System.out.println("Please try again: ");
}
}while(!password.equals(guess));
}
I have edited your code. However, I have added it to a static void:
I have also added an int to be shown if the first attempt was incorrect. Hope you like it.
class s{
public static void check(){
int attempts = 0;
String password = "Shippuden345";
System.out.println("Enter or guess the password: ");
Scanner scanner = new Scanner(System.in);
String guess = scanner.nextLine();
System.out.println(password.equals(guess));
while(attempts < 5){
if (password.equals(guess) && attempts == 0) {
System.out.println("Your guess was correct");
return;
}
else
if (password.equals(guess) && attempts > 0) {
System.out.println("Attempt number "+attempts+" was correct.");
return;
}
else{
System.out.println("Please try again: ");
attempts++;
guess = scanner.nextLine();
}
}
}
public static void main(String[] args) {
check();
}
}```
You can put the input and processing of the input value inside an infinite loop (e.g. while(true){}) which you can break on the correct input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String password = "Shippuden345";
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter or guess the password: ");
String guess = scanner.nextLine();
if (password.equals(guess)) {
System.out.println("Your guess was correct");
break;
} else {
System.out.println("Please try again: ");
}
}
}
}
A sample run:
Enter or guess the password: aSD
Please try again:
Enter or guess the password: 12H
Please try again:
Enter or guess the password: Shippuden345
Your guess was correct
You can use a loop that starts after the first guess of passwords if the guess is incorrect and continues the loop if passwords entered in the following trials are incorrect.
Then breaks the loop when the password matches and prints the congratulate message.
Related
i'm thinking of adding a password on my code and also a section where I could insert a message after logging-in. I am still new on how things work on Java so I kindly need your help to this project.
Here is my code:
import java.util.Scanner;
public class Lab2_PreFinal {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
boolean t = true ;
System.out.println("Enter your student number: ");
String studentNum = sc.nextLine();
if(studentNum.matches("[0-9]{4}-[0-9]{2}-[0-9]{3}") == t) {
System.out.println("You have successfully logged in! ");
} else {
System.out.print("Your student number is incorrect. Please try again.");
}
}
}
Thank you.
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 1 year ago.
As the title says, i'm attempting to make my program re-ask for user input if the given input is invalid (In this case, invalid input is any input that is not an integer)
I've already tried this, but it does not work:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input your age");
if (scanner.hasNextInt()) {
int age = scanner.nextInt();
System.out.println("Your age is: " + age);
System.out.println();
} else {
System.out.println("This input is not an integer - Please try again!");
int age = scanner.nextInt();
System.out.println("Your age is: " + age);
System.out.println();
}
}
}
I'm aiming for this to be done with while loop and scanner
My current code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input your age");
if (scanner.hasNextInt()) {
int age = scanner.nextInt();
System.out.println("Your age is: " + age);
}
}
}
Any reply on this post is greatly appreciated.
You can use while-loop:
Scanner scanner = new Scanner(System.in);
boolean ageGiven = false;
while (!ageGiven) {
System.out.println("Please input your age");
String next = scanner.next();
try {
int age = Integer.parseInt(next);
System.out.println("Your age is: " + age);
ageGiven = true;
} catch (NumberFormatException e) {
System.out.println("This input is not an integer - Please try again!");
}
}
I think you should put while instead of if statement. Break after having correct input. Try out once.
As you suggested, a while loop is more appropriate to this.
Something like this should work:
Scanner scanner = new Scanner(System.in);
System.out.println("Please input your age");
boolean isValid = false;
int age;
while (!isValid) {
if (scanner.hasNextInt()) {
age = scanner.nextInt();
isValid = true;
}
else {
System.out.println("Invalid input. Please type a number");
}
}
System.out.println("Your age is: " + age);
In this case, it would loop while the IsValid boolean is false. And that variable would be set to true, once the user inputs a valid age.
Edit: Changed the code to check if the input is an integer.
I'm working on a project in Java that is kind of like a digital time-machine, it basically saves what happened on a specific sate, archives it to a specific file, and stores it in a directory somewhere for safe keeping. Right now I'm working on a password function. I have the basics down for checking if it's right or wrong, but when I input the wrong answer, the class ends after saying "Invalid Password".
Is there a way to have it loop from the end of else statement to the beginning of main so I don't have to re-execute the class everytime?
import java.util.Scanner;
import java.util.*;
public class Adam {
public static void main(String args[]) {
String passwrd = "password";
String inputPassword;
System.out.print("Please Input Password ");
Scanner sc = new Scanner(System.in);
inputPassword = sc.nextLine();
if (inputPassword.equals(passwrd)) {
System.out.println("Password Accepted, Loading Archive...");
} else {
System.out.println("Invalid Password");
}
}
}
You can use a do while loop, if user input is invalid then continue the loop else not.
import java.util.Scanner;
import java.util.*;
public class Adam {
public static void main(String args[]) {
String passwrd = "password";
String inputPassword;
boolean b = true;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Please Input Password ");
inputPassword = sc.nextLine();
if (inputPassword.equals(passwrd)) {
System.out.println("Password Accepted, Loading Archive...");
b = false;
} else {
System.out.println("Invalid Password");
b = true;
}
} while (b);
}
}
DEMO
Whenever you want to run some code, check the result and then repeat if necessary the most obvious structure is do while.
Something like the following:
String inputPassword = null;
do {
if (inputPassword != null)
System.out.println("Invalid password");
System.out.println("Enter password");
inputPassword = sc.nextLine();
} while (!inputPassword.equals(password));
public static void main(String args[]) {
String password = "password";
String inputPassword;
while(inputPassword == null || !inputPassword.equals(password)){
System.out.print("Please Input Password ");
Scanner sc = new Scanner(System.in);
inputPassword = sc.nextLine();
if (!inputPassword.equals(password)) {
System.out.println("Invalid Password");
}
}
System.out.println("Password Accepted, Loading Archive...");
}
It's a good idea to have a limited number of tries to input the password. For example to have three tries to enter password, you'd have this code:
Scanner sc = new Scanner(System.in);
for (i = 0; i < 4; ++i) {
System.out.print("Please Input Password ");
inputPassword = sc.nextLine();
if (inputPassword.equals(passwrd)) {
System.out.println("Password Accepted, Loading Archive...");
break;
}
else {
System.out.println("Invalid Password");
}
}
Just put whole code into while(true) loop which you will break if password is walid
public static void main(String args[])
{
String passwrd = "password";
String inputPassword;
while(true)
{
System.out.print("Please Input Password ");
Scanner sc = new Scanner(System.in);
inputPassword = sc.nextLine();
if (inputPassword.equals(passwrd))
{
System.out.println("Password Accepted, Loading Archive...");
break; //here you are getting out of loop
}
else
{
System.out.println("Invalid Password");
//you are not breaking loop so the program will return to the beggining
}
}
}
I have added one while loop and one flag in your program. Please have a look:
public static void main(String[] args) {
String passwrd = "password";
boolean wrongPassword = true;
while(wrongPassword){
String inputPassword;
System.out.print("Please Input Password ");
Scanner sc = new Scanner(System.in);
inputPassword = sc.nextLine();
if (inputPassword.equals(passwrd)) {
System.out.println("Password Accepted, Loading Archive...");
wrongPassword = false;
}
else {
System.out.println("Invalid Password");
}
}
}
use a do-while loop :
String passwrd = "password";
String inputPassword ="";
Scanner sc = new Scanner(System.in);
do{
System.out.print("Please Input Password ");
// get the password from user
inputPassword = sc.nextLine();
// if password matches print success and break out of loop
if (inputPassword.equals(passwrd)) {
System.out.println("Password Accepted, Loading Archive...");
break;
}
else{
System.out.println("Invalid Password");
}
}while(true);
Use a do-while loop. Also, your code has some security issues:
Don't use System.in for passwords. Use Console instead. (However, if you run the program from an IDE, you may not have a Console. In that case, use a GUI method instead.)
Hash your password straight after you input it.
Clear your password buffer as soon as possible after input (i.e. overwrite it). See Console documentation.
Console con = System.console();
if (con == null)
throw new IOException("This JVM has no console");
boolean pwdCorrect;
do {
char[] inputPassword = con.readPassword("Please input password: ");
String hashedInputPassword = hashPassword(inputPassword); // search Internet for how to hash a password
for (int i = 0; i < inputPassword.length; i++)
inputPassword[i] = '\0';
pwdCorrect = isValidPassword(hashedInputPassword); // e.g. by looking it up in a password file
if (pwdCorrect)
System.out.println("Password accepted. Loading archive...");
else
System.out.println("Invalid password.");
} while (!pwdCorrect);
I've a problem with my while loop.
It works fine if the while loop conditions is false(when the password is wrong), but when the password is right it writes both You are logged in and Wrong password.
I understand why it does so but I don't understand how to solve the problem. I need to use a while loop because it's a school assignment that requires it.
import java.util.Scanner;
public class Password {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
System.out.println("Write your password: ");
String scan = scanner.nextLine();
while(scan.equals(rightPassword)){
System.out.println("You are logged in");
break;
}
System.out.println("Wrong password");
}
}
What you should have done is :
import java.util.Scanner;
public class Password {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
String scan="";
while(true){
System.out.println("Write your password: ");
scan = scanner.nextLine();
if(scan.equals(rightPassword)) {
System.out.println("You are logged in");
break;
} else {
System.out.println("Wrong password");
}
}
}
}
In this what we do is we have an endless for loop which will not break until you supply the right password. You can add some kin of number of tries to this as a breaking condition too.
Based on the comment I know, it become a infinite loop and that's why i use break. My requirement is that i must use a While loop. I know how to use a if-loop to solve the problem. Your solution should look like :
import java.util.Scanner;
public class Password {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
System.out.println("Write your password: ");
while(!rightPassword.equals(scanner.nextLine())) {
System.out.println("Wrong password");
System.out.println("Write your password: ");
}
System.out.println("You are logged in");
}
}
You can use below code.
int a=1;
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
System.out.println("Write your password: ");
String scan = scanner.nextLine();
while(scan.equals(rightPassword)){
System.out.println("You are logged in");
a=0;
break;
}
if(a==1){
System.out.println("Wrong password");
}
without changing your code this will help you.
import java.util.Scanner;
public class Password {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
System.out.println("Write your password: ");
String scan = scanner.nextLine();
while(scan.equals(rightPassword)){
System.out.println("You are logged in");
break end;
}
System.out.println("Wrong password");
end:
}
}
You may have a couple of things backwards. Check for a wrong password, not a right one in the loop, and ask for their password again. This way you will receive one message from the system and that's a bad password, or a good one once they 'successfully log in'.
import java.util.Scanner;
public class Password {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
System.out.println("Write your password: ");
String scan = scanner.nextLine();
while(!scan.equals(rightPassword)){
System.out.println("Wrong password. Please try again");
System.out.println("Write your password: ");
String scan = scanner.nextLine();
}
System.out.println("You are logged in");
}
}
Well for instance, the program will ask the user for input, then it will produce some output then it's done, but how can I make it loop again if the user wants to through the main method?
Here's my code:
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
System.out.print("Please enter the first name of the person you would love to know about : ");
String hisName = sc.next();
printSomeInfoAbout(hisName);
}
How will I make it run again if the user decides to again?
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
System.out.print("Please enter the first name of the person you would love to know about : ");
String hisName = sc.next();
printSomeInfoAbout(hisName);
System.out.print("AGAIN (Y/N) : "); // ask the input from user
String var= sc.next();
if(var.equalsIgnoreCase("Y")){// Matches "Y" or "y"
main(null); // if input is Y then call main again.
}
}
String x=null;
Scanner sc = new Scanner(System. in );
String hisName=null;
do{
System.out.print("Please enter the first name of the person you would love to know about : ");
hisName = sc.next();
printSomeInfoAbout(hisName);
System.out.print("y/n");
x=sc.next();
}while(x.equals("y"));
boolean exit = false;
while(!exit){
Scanner sc = new Scanner(System. in );
System.out.print("Please enter 'exit' to exit or, the first name of the person you would love to know about : ");
String hisName = sc.next();
if(!"exit".equals(hisName)) {
printSomeInfoAbout(hisName);
}else{
exit = true;
}
}
create a method for getting the input and call on it if the user chooses to input another name
A simple loop that will check whatever the user put an empty string as the first name it will exit.
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
do {
System.out.print("Please enter the first name of the person you would love to know about : ");
String hisName = sc.next();
if (hisName.equals("")) {
printSomeInfoAbout(hisName);
}
} while (!hisName.equals(""));
}
Please find below code segment, It might help you..
public static void main(String[] args) {
String name;
Scanner scn = new Scanner(System.in);
boolean flag = false;
do {
System.out.println("Please enter the first name of the person you would love to know about : ");
name = scn.next();
System.out.println("Your friend " +name+ " is a great guy..!");
System.out.println();
System.out.println("Enter 1 to continue giving other" +
" names or Enter 2. to quit");
System.out.println();
int choice = scn.nextInt();
if( choice == 1 ) {
flag = true;
} else {
System.out.println("ThankU.. Bye");
flag = false;
}
} while(flag);
}