Cannot get code to terminate after enters correct answer - java

Write a program called PasswordChecker that does the following:
1. prompts the user to enter a password
2. prompts the user to renter the password
3. checks to ensure that the two password entries are identical
4. (for the first three attempts) Repeats steps 1 through 3 until the password is correctly entered twice.
5. After the 3rd attempt, if the user doesn’t enter the password correctly, the program needs to display an informative message indicating user account is suspended.
My code:
import java.util.Scanner;
public class passwordChecker{
public static void main(String [] args){
String pw1;
String pw2;
int count=0;
Scanner keyboard = new Scanner(System.in);
do{
System.out.println("Enter the password:");
pw1 = keyboard.nextLine();
System.out.println("Renter the password:");
pw2 = keyboard.nextLine();
count++;
if(pw1.equals(pw2))
System.out.println("Correct");
else if(count>=3)
System.out.println("Account is suspended");
while(pw1==pw2||count>3);
}
}

You seem to be missing a closing brace (you open the do but don't close before while). Your first condition should be count < 3 and I think you want to loop while the two String(s) are not equal. Something like,
do {
System.out.println("Enter the password:");
pw1 = keyboard.nextLine();
System.out.println("Renter the password:");
pw2 = keyboard.nextLine();
count++;
if (pw1.equals(pw2)) {
System.out.println("Correct");
} else if (count >= 3) {
System.out.println("Account is suspended");
}
} while (count < 3 && !pw1.equals(pw2));
Edit
The reason you don't use == (or !=) for Object types is that it tests reference equality only. You want to test for value equality (these String(s) came from different lines, so they won't compare equal by reference).

Do it simply
public class PasswordChecker {
public static void main(String[] args) {
String pw1;
String pw2;
int count = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the password:");
pw1 = keyboard.nextLine();
while(true){
System.out.println("Renter the password:");
pw2 = keyboard.nextLine();
if (pw1.equals(pw2)) {
System.out.println("Correct");
break;
} else if(count == 3){
System.out.println("Account is suspended");
break;
}
count++;
}
}
}

Related

JAVA scanner causes if statement problems when using bag

I am new to JAVA and have been using IDE, to cut it short whenever I try to check if bag contains a string thats the same as the given input JAVA counts it as FALSE, even if the if statements such as "is input equal to 1" and "is 1 inside the bag" pass as true. here is an excerpt from my code, I would appreciate any help and advice.
//user input
System.out.println("Please enter a string (to exit, enter 'exit'): ");
a=sc.next();
if (a.equals("1")) {System.out.println("adpkgnosıfbgojadnofabsndofgna");}
if (ValidAnswers1.contains("1")) {System.out.println("adpkgnosıfbgojadnofabsndofgna");}
//error detection. after I learn bag it will become if bag contains string s.
if (ValidAnswers1.contains(a)) {correct_input=1;} else {correct_input=0;}
while (correct_input==0)
{
System.out.println("you entered:"+ a+".");
System.out.println("Please enter a valid string (to exit, enter 'exit')");
a = sc.next();
if (ValidAnswers1.contains(a)) {correct_input=1;} else {correct_input=0;}
}
the console prints out both the keymashes and then diverts into the while loop. I have checked to make sure the while loop is correct by testing with fixed variables, but when scanner is used it seems to have an error.
I didn't understand, what you really want, i did the test and a yet is working fine. take a look at the class, maybe is some error in the variables or something
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String a;
String ValidAnswers1 = "1";
int correct_input = 0;
//user input
System.out.println("Please enter a string (to exit, enter 'exit'): ");
a = sc.next();
if (a.equals("1")) {
System.out.println("adpkgnosıfbgojadnofabsndofgna");
}
if (ValidAnswers1.contains("1")) {
System.out.println("adpkgnosıfbgojadnofabsndofgna");
}
//error detection. after I learn bag it will become if bag contains string s.
if (ValidAnswers1.contains(a)) {
correct_input=1;
} else {
correct_input=0;
}
while (correct_input==0) {
System.out.println("you entered:"+ a+".");
System.out.println("Please enter a valid string (to exit, enter 'exit')");
a = sc.next();
if (ValidAnswers1.contains(a)) {
correct_input=1;
} else {
correct_input=0;
}
}
}
Here is the output:
Please enter a string (to exit, enter 'exit'):
a
adpkgnos?fbgojadnofabsndofgna
you entered:a.
Please enter a valid string (to exit, enter 'exit')
1
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
//Create a new Object Scan in the memmory
Scanner scan = new Scanner(System.in);
String input;
String[] validAnswers = new String[]{"1","2","3","exit"};
boolean isCorrect = false;
//The method equalsIgnoreCase means that the text can be in uppercase too;
/*The number between the tags "[]" means the number in the array since arrays
starts with number "0" */
do{
System.out.println("Please enter a string (to exit, enter 'exit'): ");
input = scan.next();
if(input.equalsIgnoreCase(validAnswers[0])){
isCorrect = true;
System.out.println("Number 1");
}else if(input.equalsIgnoreCase(validAnswers[1])){
isCorrect = true;
System.out.println("Number 2");
}else if(input.equalsIgnoreCase(validAnswers[2])){
isCorrect = true;
System.out.println("Number 3");
}else if(input.equalsIgnoreCase(validAnswers[3])){
isCorrect = true;
System.out.println("EXIT!");
//You could use the method System.exit(0) to finish the program;
//If you put "1" in the exit value means that the prgram finished with some error;
//System.exit(0);
}else{
//If the Answers is different from all of the others;
System.out.println("you entered: " + input +".");
System.out.println("Please enter a valid string (to exit, enter 'exit')");
}
}while(isCorrect != true);
//I used the method do{}while because it's the only method that will exacute at least once;
}

Loops in Java after user inputs values

public static void main(String args[])throws IOException{
validNumbers = new int[200];
Scanner sc1 = new Scanner(new File("validNumbers.txt"));
int i = 0;
while(sc1.hasNextInt()) {
validNumbers[i++] = sc1.nextInt();
}
// Creating loop for what the user enters
boolean newValidator = true;
Scanner scanner = new Scanner(System.in);
while(newValidator) {
System.out.print("Enter the account number: ");
String num = scanner.nextLine();
// If found, the calculations will get displayed
if(validator(num)) {
System.out.print("The calculated value to this account is: " + calculator(num));
newValidator = false;
System.out.println("\n" + "Would you like to enter another account number? (y/n)");
String ans = "";
ans = scanner.nextLine();
// Needed the false, if not the code would keep asking to "Enter account number: "
if (ans.equals("y")) {
System.out.print("Enter the account number: ");
String num2 = scanner.nextLine();
System.out.print("The calculated value to this account is: " + calculator(num2));
} else if(ans.equals("n")) {
newValidator = false;
System.out.println("** Program Exit **");
}
}
// Wanted to add a loop for the user to decide if they want to continue iff wrong account is inputed
else {
System.out.println("Not valid account number" + "\n\n" + "Would you like to try again? (y/n)");
String ans = "";
ans = scanner.nextLine();
if(ans.equals("y")) {
newValidator = true;
}
// How the program terminates if the user does not wish to continue
else if(ans.equals("n")) {
newValidator = false;
System.out.println("Not valid input, the program is now terminated!");
}
}
}
}
}
(Using Java) The code is doing the following:
1.) When the user enters a correct number it sees the number(in the file) and adds the digits
2.) When it is not in the file, it knows the number is not there and tells the user to try again and if the user doesn't want to, it ends the program.
***** (Using Java) What the code is not doing:
1.) After they entered the right code, the program is to ask the user if they want to enter another account(with the adding of an account if so). Then this is where I have the problem, the loop is ending after this second go and I need it to keep asking if they want to enter another account number unit the user wants to exit.*****
There's no need to have a nested question asking for another account number, the while loop itself will ask the user again when it repeats.
Simply ask the user if they want to enter another and then exit the loop if the don't. The while loop drops out when "newValidator" is set to false:
boolean newValidator = true;
while(newValidator) {
System.out.print("Enter the account number: ");
String num = scanner.nextLine();
if(validator(num)) {
System.out.println("The calculated value to this account is: " + calculator(num));
}
else {
System.out.println("Not valid account number!");
}
System.out.println("\n\nWould you like to enter another account number? (y/n)");
String ans = scanner.nextLine();
if (ans.equals("n") || ans.equals("N")) {
newValidator = false;
}
}
System.out.println("** Program Exit **");

Creating and validating a reference number

So basically, I need to get the user to enter a reference number; it cannot be automatically generated.
It needs to be 2 Numbers, a Letter and a Number again.
Here's my code, but I cannot for the life me get it working, I had it working via a way that automatically generates a reference number, but now we need to change it so it gets the user to manually generate one and I'm just sat staring at NetBeans like "Oh errmmmm..."
static String getReferenceNumber() {
Scanner refScanner = new Scanner(System.in);
String referNumber = null;
System.out.println("Please enter a Reference Number");
System.out.println("It must be 2 Letters and 3 Numbers and a Number");
String input = refScanner.nextLine().toUpperCase();
while (!Policy.refCheck(input)) {
System.out.println("Please enter a Reference Number");
System.out.println("It must be 2 Letters and 3 Numbers a Nuber");
if (input.length() !=5) {
referNumber = false;
} else if ((!Character.isLetter(input.charAt(0)))
||!Character.isLetter(input.charAt(1))
||!Character.isDigit(input.charAt(2))
||!Character.isDigit(input.charAt(3))
||!Character.isDigit(input.charAt(4))){
referNumber = false;
}
System.out.println("");
System.out.println(referNumber);
return referNumber;
}
You never assign the actual input to the referNumber, instead you just assign Booleans?
Therefore at the end you are returning a Boolean or null when the return value needs to be a string.
static String getReferenceNumber() {
Scanner refScanner = new Scanner(System.in);
String referNumber = "";
boolean test = false;
while (!test) {
System.out.println("Please enter a Reference Number");
System.out.println("It must be 2 Letters and 3 Numbers:");
String input = refScanner.nextLine().toUpperCase();
if (input.length() !=5) {
test = false;
System.out.println("Invalid reference");
} else if ((!Character.isLetter(input.charAt(0)))
||!Character.isLetter(input.charAt(1))
||!Character.isDigit(input.charAt(2))
||!Character.isDigit(input.charAt(3))
||!Character.isDigit(input.charAt(4))){
test = false;
System.out.println("Invalid reference");
} else {
referNumber = input;
test = true;
}
}
System.out.println(referNumber);
return referNumber;
}
I have changed the condition for the while loop and altered your if statements. I hope this helps.

Using java scanner to check two conditions while taking user input

I need to user to enter an int between 1 and 301.
I have this simple loop here to check for user input.
I just want a single number from the user, and if the user enters anything other than an int between 1 and 301, I want to display the print line and prompt the users to try again until they enter a valid input.
while (!sc.hasNextInt()) {
System.out.print("Invalid Input. Please enter a valid number between 1 and 301: ");
sc.next();
}
int numToCheck = sc.nextInt();
// do stuff with numToCheck
This checks that the input is an int, but I can't seem to find a way to give the int input a bound. I tried to assign the user input to a variable and then check the conditions input < 1 or input > 301, but I get InputMismatchException if user enters a letter. How should I store the user input? (I want to store it as an int to check the conditions, but can't do that since I don't know what the user will enter).
Perhaps there is a better design to accomplish all this. Those are welcomed too.
Thanks in advance.
You're not saving the value of the of the input. So your program is waiting on the user to enter a number each time it see "sc.nextInt()" Assign the input to a variable, and then check the condition.
EDIT: okay, I'll go the extra mile for you. See if this works.
***Accounted for the case where the user might enter a character instead of a number.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int input;
while (true){
if (sc.hasNextInt()){
input = sc.nextInt(); // Assign the next integer to a variable
if (input <= 301 && input >= 1){ // Check if integer meets condition
break; // Condition met, break out of loop
}
}else{
sc.next();
}
System.out.println("Invalid Input. Please enter a valid number between 1 and 301: ");
}
}
}
I ran this code, to see if it would show a better performance than yours.
Scanner sc = new Scanner(System.in);
boolean valid = true;
do {
if (!valid) {
System.out.print("Invalid Input. ");
}
System.out.print("Please enter a valid number between 1 and 301: ");
String input = sc.next();
try {
int value = Integer.parseInt(input);
valid = (value >= 1 && value <= 301);
} catch (NumberFormatException nfex) {
valid = false;
}
} while (!valid);
When the conversion to integer fails, the JVM hangs a little. I believe your problem has more to do with the try / catch mecanism that Scanner performs under the hood, than with design.
Assuming you want only 1 input from the user, try following simple code, which takes input from the user until user enters a valid input.
Scanner in = new Scanner(System.in);
int flag = 0,x=0;
while(flag == 0){
x = in.nextInt();
if(x<1 || x>301){
flag = 0;
System.out.println("Invalid Input.");
}
else{
flag = 1;
}
}
And if you want user to input more than 1 inputs (i.e 3 here), than set a counter that increases with every valid input of the user, as following:
Scanner in = new Scanner(System.in);
int flag = 0,x=0,count = 1;
while(flag == 0){
x = in.nextInt();
if(x<1 || x>301){
flag = 0;
System.out.println("Invalid Input.");
}
else{
//executes when input is valid
if(count == 3){
flag = 1;
}
count++;
}
}
Edit:
If you also want to check whether the input is Integer or not, than you have to add one extra condition in above code. And as you said you want only one input from user rather than 3, you have to change exit condition. Change code as following:
Scanner in = new Scanner(System.in);
int flag = 0,count = 1,x=0,flag1 = 0;
String y;
while(flag == 0){
y = in.next();
flag1 = 0;
try{
x = Integer.parseInt(y);
}
catch(NumberFormatException e){
flag1 = 1;
System.out.println("Invalid Input.");
}
if((x<1 || x>301)&&flag1 == 0){
flag = 0;
System.out.println("Invalid Input.");
}
else if(flag1 == 0){
//executes when input is valid
if(count == 1){ // put count == 3 if you want 3 inputs from user.
flag = 1;
}
count++;
}
}
Here we are taking the input as a String and than converting the String into the Integer by using Integer.parseInt(). If the String is not Integer, than it will throw the exception and we will continue the loop till the valid input is entered by the user.
Use DO WHILE for result
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
OK ?

Java Input not working (Beginner)

For some reason, my code will not accept input on the last line "What would you like to order: "
Could anyone tell me what my error is here? It is compiling correctly and everything. I am only a beginner so please tell me in basic terms.
import java.util.Scanner;
import java.util.*;
class RestaurantMain {
public static void main(String[] args)
{
//Create an array list
ArrayList menu = new ArrayList();
//Variables//
int choice;
int customerChoice;
boolean trueFalse;
int restart = 0;
String choice2;
String addItems = "";
int menuCount = 0;
int indexCount = 0;
String item = "";
//Import input device
Scanner in = new Scanner(System.in);
ArrayList theMenu = new ArrayList();
System.out.println("Welcome to the Cooper's restaurant system!");
System.out.println("How can I help?");
System.out.println("");
System.out.println("1. Customer System");
System.out.println("2. Management System");
System.out.println("");
System.out.println("");
System.out.print("Which option do you choose: ");
choice = in.nextInt();
if (choice == 1) {
System.out.println("Our menu's are as follows:");
System.out.println("");
System.out.println("1. Drinks");
System.out.println("2. Starters");
System.out.println("3. Mains");
System.out.println("4. Desserts");
System.out.println("");
System.out.println("Please note - You MUST order 5 items.");
System.out.println("");
System.out.print("What menu would you like to follow? ");
customerChoice = in.nextInt();
if (customerChoice == 1) {
System.out.println("Drinks Menu");
System.out.println("Would you like to order? ");
choice2 = in.nextLine();
if (choice2 == "yes") {
System.out.println("Please enter the amount of items you want to order: ");
while (indexCount <= menuCount);
System.out.println("Please enter your item: ");
item = in.nextLine(); {
theMenu.add(item);
}
}
}
if (customerChoice == 2) {
System.out.println("Starters Menu");
}
if (customerChoice == 3) {
System.out.println("Mains menu");
}
if (customerChoice == 4) {
System.out.println("Desserts Menu");
}
You need to call in.nextLine() right after the line where you call in.nextInt()
The reason is that just asking for the next integer doesn't consume the entire line from the input, and so you need skip ahead to the next new-line character in the input by calling in.nextLine()
customerChoice = in.nextInt();
in.nextLine();
This pretty much has to be done each time you need to get a new line after calling a method that doesn't consume the entire line. Consider using a BufferedReader object instead!
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int integer = Integer.parseInt(reader.readLine());
This will throw the same errors that Scanner.nextInt() does if the input can't be parsed as an integer.
Regarding your comment about errors, there is one:
while (indexCount <= menuCount);
System.out.println("Please enter your item: ");
item = in.nextLine(); {
theMenu.add(item);
}
}
Should instead be like the following:
while(indexCount <= menuCount){
System.out.println("Please enter your item: ");
item = in.nextLine();
theMenu.add(item);
}
Also, it isn't strictly necessary, but I suggest that you do declare the ArrayList's generic type when instantiating the list, so that further calls to theMenu.get() don't need to be casted to a String.
ArrayList<String> theMenu = new ArrayList<String>();
When comparing strings, ensure that you use the str.equals("string to compare with") method, instead of the equality operator (==). Therefore for example, choice2 == "yes" should instead be choice2.equals("yes"). Using equalsIgnoreCase instead of equals would ignore case differences, which may be useful in this situation.
insted of in.nextLine(); function you just try another scanner functions like 'in.next()'. just R&D with the methods that already give the JVM itself.
you just use correct the logic and use equal() or equlIgnoreCase() methods insted of "=" operator.

Categories

Resources