this i my first attempt at asking a question so hopefully it shows correctly. Basically what I need the program to do is to ask the user for a preset account number and password and only allow them 3 attempts. I then want to call up another method when both requirements are met so i can continue with the program. The first problem i have is that when i enter the correct password its is still showing as incorrect and i don't know why, then i would like to know if i have call the method within the if statement correctly. Thanks.
import java.util.Scanner;
public class Part4 {
public static void main(String[] args)
{
String password = "password", passwordattempt = null;
int accnum = 123456789, acctry = 0, tries = 0;
Scanner input = new Scanner (System.in);
while (acctry != accnum){
System.out.println("\nPlease enter your account number");
acctry = input.nextInt();
if (acctry != accnum)
System.out.print("That number is incorrect. Please try again.");
else
if (acctry == accnum)
{
while (tries < 3)
{
System.out.println("\nPlease enter password");
passwordattempt = input.next();
if (passwordattempt != password){
System.out.print("That password is incorrect");
tries++;
}
else
if (passwordattempt == password){
System.out.print("That is correct");
AccountDetails.Details(args);
}
}
System.out.print("\nYou have exceeded the ammount of tries");
}
}
}
public static class AccountDetails {
private static void Details(String[] args){
System.out.print("it works");
}
}
}
two problems.
1: You're executing your while loop regardless of if it is successful or not.
.
while(tries < 3)
should be
while(tries < 3 && !successfulPassword)
You'll need to add the successfulPassword variable, so that you don't get it right the first time and yet continue to have to enter passwords.
2: Your comparison of strings is grossly, umm, well, wrong. There's two things that catch my eye. The first is you can't use == and != and get the results you expect. You must use .equals(). Secondly, you don't need to repeat the opposite clause like you do with a human. For example, I tell my daughter "If you eat your supper, then you may have cookies. Else, if you do not eat your supper, then you may not have cookies." To a computer, you don't need that last "if you do not eat your supper". It's guaranteed to be true (since you're in the else block anyway) and it just clutters it up. So that just becomes
.
if(passwordAttempt.equals(password) {
successfulPassword = true;
} else {
tries++;
}
In the Java language, Strings are objects, and thus comparing them using '==' is testing by reference, and not by equality.
I believe what you are looking for is
if (passwordattempt.equals(password)) {
Check here for more information:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#equals(java.lang.Object)
Related
Need to make a password program, where the user sets a password at the beginning and the password can be entered 3 times before the program is stopped. The program can not be case sensitive.
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int attempts = 3;
String password = "";
System.out.println("Please input your password.");
Scanner stringScanner = new Scanner(System.in);
String PASSWORD = stringScanner.next();
while (attempts-- > 0 && !PASSWORD.equals(password)) //compares and then decrements
{
System.out.print("Enter your password: ");
password = sc.nextLine();
if (password.equals(PASSWORD))
System.out.println("Access Granted");
else
System.out.println("Incorrect. Number of attempts remaining: " + attempts);
}
if (attempts < 1) {
System.out.println("You have entered too many incorrect passwords, please try again later.");
}
else {
System.out.println("Secret: Water is not Wet.");
}
}
}
Program prints as expected, but is not case sensitive
The first part of your question says The program can not be case sensitive while afterwards you are stating that Program prints as expected, but is not case sensitive, so it's a little difficult to understand what you want. But by looking at the code and seeing that it is doing a case-sensitive comparison, and that you are not happy with it's behavior, I'm guessing you want this to be a case-INsensitive comparison.
In that case, you can use String#equalsIgnoreCase: !PASSWORD.equalsIgnoresCase(password)
simply if you need not to consider the case sensitive just do password.equalIgnoreCase(PASSWORD)
but if you need to be sure that both have same case sensitive you can just convert both variables to .toUpperCase before the comparison
I'm having issues understanding nested loops and their behavior. On the first loop the script asks for 10 digit number otherwise it will keep looping, this works fine. on the second loop, i'm trying to get the program to keep running until users enters "999" anywhere in the phone number. I have some idea but i'm not able to put it together. so if the user enters a 10 digit number but it doesnt contain 999, then it will keep asking to reenter phone number.
import javax.swing.JOptionPane;
import java.lang.*;
public class FormatPhoneNumber {
public static void main(String[] args) {
final int numLength=10;
String phoneNum = null;
String nineS="999";
phoneNum=JOptionPane.showInputDialog(null, "Enter your telephone number");
while (phoneNum.length()!=numLength)
{phoneNum=JOptionPane.showInputDialog(null, "You must re-enter 10 digits as your telephone number.");
}
StringBuffer str1 = new StringBuffer (phoneNum);
str1.insert(0, '(');
str1.insert(4, ')');
str1.insert(8, '-');
JOptionPane.showMessageDialog(null, "Your telephone number is " +str1.toString());
while (phoneNum.contains(nineS))// THIS IS THE ISSUE
{
}
}
}
Use
if (phoneNum.contains(nineS))
{}
don't use
while (phoneNum.contains(nineS))
or U can do it this way
if (!(phoneNum.contains(nineS)))
{
JOptionPane.showMessageDialog(null,"Invalid Input");
}
Nesting is when one loop is inside another loop. The code you have provided does not have one.
Typical example of nesting:
while( some_condition )
{
do_something..
while( more_condition )
{
do_something_more..
}
}
If I understand correctly, you want to keep on entering numbers and do something with them. But once the user enters a number which has '999' in it, the control has to come out of the loops.
As someone already pointed out, you do not need nested loop to achieve this at all.
while( phoneNumber has 10 digits )
{
do_something..
if( phoneNumber has '999' anywhere )
{
break;
}
}
while (phoneNum.length()!=numLength)
{
phoneNum=JOptionPane.showInputDialog(null, "You must re-enter 10 digits as your telephone number.");
StringBuffer str1 = new StringBuffer (phoneNum);
str1.insert(0, '(');
str1.insert(4, ')');
str1.insert(8, '-');
JOptionPane.showMessageDialog(null, "Your telephone number is " +str1.toString());
if(phoneNum.contains(nineS))// THIS IS THE ISSUE
break;
}
hope this helps.
I am trying to use the while loop for re-running parts of code in my simple program. In this program, the user makes a simple account, types in a verification number, then signs in. Once signed in, I wish to allow the user to sign out, edit his profile settings and more. However I have a small problem.
Say the user has just edited their account settings. Instead of the program terminating, I want them to be able to return to the "menu".
The problem lies with how to do that. As there is no goto statement in java, from what I have read, I must use the while loop. I have no idea of how to go about that. I just can't wrap my head around it. Loops have always confused me. Also, should I even use the while loop? Would it be better to use the for or do-while loops? And what expression should I use? Will I need the break statement?
I know it isn't a concrete question, but any help that puts me on the right path is well appreciated.
Below is the full code for reference.
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);
int code = userInput.nextInt();
if (code == randm) {
System.out.println("Thank you, " + userName);
System.out.println("You may now login. Begin by entering your username");
//Where I would go if the user signed out
String name = userInput.next();
if (name.equals(userName)) {
System.out.println("Now please enter you password");
String pass = userInput.next();
if (pass.equals(passWord)) {
System.out.println("Thank you. You have now successfully logged in");
//Where the "main menu" will be
//Rest of code will also go here
}
else {
System.out.println("Password is incorrect");
}
}
else {
System.out.println("Username is incorrect");
}
}
else {
System.out.println("The code entered is incorrect.");
}
}
else {
System.out.println("Invalid Password");
}
}
else {
System.out.println("Invalid Username");
}
}
You have placed a comment //where would I go if the user signed out?
The answer is, You will show the message to sign in when he is signed out, so that he can sign in again. You can do this by using for loop or loop or whatever loop you want. That means the part of user login will be in a loop, if the user logged in then the menu will be shown up. If the user sign out, the sign in form will be shown up infinitely.
You can put your code inside do. It will not break and will keep looping.
do{
}
while(true);
I am trying to check if a user entered a number and if not, then it uses a default number like 10. How do i check if the user just presses enter and doesn't enter anything in Java
input = scanner.nextInt();
pseudo code:
if(input == user just presses enter without entering anything){
input = 10;
}
else just proceed with input = what user entered
//scanner is a Scanner
int i; // declare it before the block
try {
i = scanner.nextInt();
}
catch (InputMismatchException ime) {
i = 10;
}
// i is some integer from the user, or 10
First things first, geeeeeez guys, when the OP says something like
"I don't want an exception, i want i = 10 if nothing is entered, so what do i do"
That should clue you in that he probably doesn't know too much about exceptions (maybe even java) and might need a simple answer. And if that's not possible, explain to him the difficult ones.
Alright, here's the plain and simple way to do it
String check;
int input = 10;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
else
{
input = Integer.parseInt(check);
}
Let me explain what this code is doing. You were originally using nextInt() to get your number for input, correct? The problem is, nextInt() only responds if the user actually inputs something, not if they press enter. In order to check for enter, we used a method that actually responds when the user presses enter and used that to ensure that our code does what we wanted to. One thing I recommend using is an API, Java has one.
Here's the link for the API HERE
And here's the link for the actual method I used HERE. You can find descriptions and instructions on many methods you'll run into on this API.
Now, back to my answer, that's the easy way to do it. Problem is, this code isn't necessarily safe. It'll throw exceptions if something goes wrong, or if someone is trying to hack into your system. For example, if you were to enter a letter instead of pressing enter or entering a number, it would throw an exception. What you've been seeing in the other answers is what we call exception handling, that's how we make sure exceptions don't happen. If you want an answer that'll catch most of these exceptions, you need to make sure your code catches them, or avoids them all together (I'm simplifying things immensely). The above answer is working code, but isn't safe code, you wouldn't ever use something like this all by itself in real life.
Here is something that might be considered safe code. And no exceptions to keep it simple! ;)
import java.util.Scanner;
public class SOQ15
{
public Scanner scanner;
public SOQ15()
{
scanner = new Scanner(System.in);
int input = 10;
boolean isAnInt = true;
String check;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
for(int i = 0; i < check.length(); i++)
{
if(check.charAt(i) >= '0' && check.charAt(i) <= '9' && check.length() < 9)
{
//This is if a number was entered and the user didn't just press enter
}
else
{
isAnInt = false;
}
}
if(isAnInt)
{
input = Integer.parseInt(check);
System.out.println("Here's the number - " + input);
}
}
public static void main(String[] args)
{
SOQ15 soq = new SOQ15();
}
}
I don't have time to go into all the details right now, but ask and I'll gladly respond when I get the time! :)
Well if you are using scanner, given the details provided, you can try:
Scanner in = new Scanner(System.in);
if in.hasNextInt(){ //Without this, the next line would throw an input mismatch exception if given a non-integer
int i = in.nextInt(); //Takes in the next integer
}
You said you wanted a default of 10 otherwise so:
else {
int i = 10;
}
I am very new to programming and need some help. I need to write a simple program that verifies an ATM users pin number. The program will either, accept the pin and exit, tell the user it was an incorrect pin and have them try again up to three times, or tell the user their card is locked because they were wrong three times. I have searched for over an hour now and cannot find an example of this. I know i will need to use a scanner and a loop to accomplish this but not much else. Any help is appreciated as it is due by midnight......
for i = 1..3
prompt user for pin
read pin
check pin
if pin is correct, exit
tell user they were wrong and try again
tell user they got it incorrect three times and their card is locked.
I will give one hint which can trip some newbies up. The pin is an integer, right? So you might be tempted to use Scanner.nextInt() to get the input--do not do that! Just get the next line and compare Strings (you may have to use String.trim() to get rid of whitespace). It's more complicated if you try to use Scanner.nextInt() (what if the user enters something that cannot be parsed as an integer).
import java.util.Arrays;
import java.io.Console;
public class atm {
public static void main(String[] args) {
int counter = 3;
int attempt = 3;
char[] ch = null;
Console c=System.console();
System.out.println("Enter PIN: ");
ch=c.readPassword();
String pass=String.valueOf(ch);
if(pass.equals("enigma")){
System.out.println("Correct PIN entered!");
}
while(!pass.equals("enigma") && attempt != 0){
System.out.println("Invalid PIN entered!. " + --attempt + " attempts remaining.");
counter--;
if(attempt != 0){
c=System.console();
System.out.println("Enter PIN: ");
ch=c.readPassword();
pass=String.valueOf(ch);
if(pass.equals("enigma")){
System.out.println("Correct PIN entered!");
}
}
else{
System.out.println("your card has locked!");
break;
}
}
}
}
Note that you can put your PIN code instead of "enigma" string, I hope that will help.
here is the implementation of pseudo code answered by #Jared above
boolean cardLockFlag = false ;
String password;
Scanner scan = new Scanner (System.in);
password = "password" ;
if(!cardLockFlag){
for(int i = 0 ; i < 3 ; i++){
if(password.equals(scan.next().trim())){
System.out.println("Success :) ");
break ;
}else{
if(i==2){
cardLockFlag = true ;
}else{
System.out.println("Wrong Password");
}
}
}
}else{
System.out.println("Card is Locked");
}