Been racking my brains with this for ages now and it's just stumped me.
I have a simple string comparison:
public static void login()
{
isIncorrectInput = true;
while (isIncorrectInput)
{
System.out.print("Please enter your password: ");
password = readLine();
if (password.equals(currentUser.password))
{
isIncorrectInput = false;
System.out.print("Successful login!");
}
else
{
System.out.print("Incorrect password. Please try again.\n");
}
}
}
So, 'password' is a String variable, currentUser is a instance of a User object which has a password property.
I've tried switching which object the method is called on: doesn't work. Tried ignoring the case: doesn't work. The passwords are DEFINITELY the same, I've stepped through it countless times, it's just returning false when it should be returning true.
What am I doing wrong!!?
Thanks in advance guys.
Without seeing readLine()'s body I can't be sure, but it is probably a whitespace issue. Try doing a trim() on the input before doing the comparison.
probably the password variable is ended with '\n' char -
try:
password = password.trim();
Where do you initalize "password" ? Is the password variable in the User-Class set and you have direct access (public etc.).
What does the "readLine()" methode do?
Maybe you miss a space character or a newline, also check if upper/lower case is the same.
Good luck.
Perhaps you need to suppress the end line character.
password.replace(System.getProperty("line.separator"),"");
Related
basically its a wordle type game where we take input and if the first letter of the input is the same as the first letter of our word "sc" it should make the textView background color to green or yellow if not in the right position
String str=editText.getText().toString();
String first=str.substring(0,1);
String sec=str.substring(1,2);
String third=str.substring(2,3);
String fourth=str.substring(3,4);
if(count==0)
{
textView1.setText(first);
textView2.setText(sec);
textView3.setText(third);
textView4.setText(fourth);
if(first==sc.substring(0,1))
{
textView1.setBackgroundColor(Color.GREEN);
}
else if(first==sc.substring(1,2)|| first==sc.substring(2,3) || first==sc.substring(3,4))
{
textView1.setBackgroundColor(Color.YELLOW);
}
i have tried this but it doesn't seem to be working it does no change
i am new to android studio code so please excuse if this has a very easy solution and i have also tried searching for similar questions online but none of them seemed to be working
In your code, you try for execute your if statement inside if(count==0). I assume you try execute your code if wordle is not fill yet since you dont explain clearly about count.
Based on your question here my answer, first you need initialize input and sc value
String sc = "WORD" \*just example value\*
String str=editText.getText().toString();
String first=str.substring(0,1);
String sec=str.substring(1,2);
String third=str.substring(2,3);
String fourth=str.substring(3,4);
Second, use if statement for check first letter is already filled
if(!first.equals(""))
Inside first if, create if statement for compare first letter with sc value
textView1.setText(first);
if(first==sc.substring(0,1))
{
textView1.setBackgroundColor(Color.GREEN);
}
else
{
textView1.setBackgroundColor(Color.YELLOW);
}
This simple way for reach your goal
== use when we have to compare integers. But you are using == to compare strings. Which is wrong. For comparing Strings you have to use string.matches() or string.equals().
Make changes in your code as below
if(count==0)
{
textView1.setText(first);
textView2.setText(sec);
textView3.setText(third);
textView4.setText(fourth);
if(first.matches(sc.substring(0,1))) // if "sc.substring(0,1)" throwing any error then parse it into "String.valueOf(sc.substring(0,1));"
{
textView1.setBackgroundColor(Color.GREEN);
}
else if(first.matches(sc.substring(1,2))|| first.matches(sc.substring(2,3)) || first.matches(sc.substring(3,4)))
{
textView1.setBackgroundColor(Color.YELLOW);
}
Let me know if the problem has not been solved yet.
I am new here and I am making a program to allow a person to sign up for something. It takes in the username, compares it with others, and if it is unique, allows it. When they enter a password however, I don't know how to make sure the word is more than 8 digits. I need to be able to compare the password with something, and only allow the password if it is more than 8 digits or not. Thanks!
You should accept the password into a String type. Then compare it with other String using String.equals(String otherWord) method and check it's length using String.length() method as shown below :-
Scanner s=new Scanner(System.in);
boolean flag=true;
String pwd="";
while(flag) {
pwd=s.nextLine();
if(pwd.length()>8 && pwd.equals("IntendedWord"))
// set flag=false AND then continue your intended action...
else
System.out.println("Please try again");
}
The method you are looking for is String.length().
Use something like:
if (password.length() > 8) {
// password is long enough
}
Try something like this:
// Previous code gets the value for the field and stores it in String pass
if ( pass.length() > 8 )
{
// it is valid. Hash and save
}
else
{
// Not valid. Let user know and ask for reentry.
}
//etc.
You could probably put this and other checking in a validate function and call it before storage.
Let me know if there is anything else you need.
Also, two things to learn about Stack Overflow as a courtesy. Please search for questions similar to yours before posting. And second, give more information when posting so people don't have to guess at what you want/need.
you could use something like
if(password.length() > 8)
{
//some logic
}
that is, considering that you have your password as a string value.
This question already has answers here:
Can't get else if statement to work in Java
(5 answers)
Closed 10 years ago.
Help. I'm new to Java programming so I'll try to make the best of your terms.
I was wondering how to get this program to register as true. When I type in "password" as an input, it does not execute any code from the "if" body. I also pasted this code in another class and it still doesn't work, regardless.
I've worked on this program for about a half an hour, and debugging it for twice as long. Please look through the coding.
import java.util.Scanner;
public class whileloop {
public void whileloop1() {
//DEBUG THIS PROGRAM! "password" does not work for input
System.out.println("Please enter the password to continue: ");
Scanner password = new Scanner(System.in);
String passwordinput = password.nextLine();
System.out.println("This is your entered password: " + passwordinput);
if (passwordinput == "password") {
System.out.println("Startup sequence has been iniciated.");
System.out.println("System is working correctly.");
//Terminate all here ---
} else {
System.out.println("Wrong password! Terminating program. /END");
}
System.out.println("Supressing the program's scanner!");
password.close();
}
}
When comparing string content in Java you use the .equals() method.
The == operator checks for reference equality, meaning, testing if they are both references of the same object.
So, in your case:
if(passwordinput.equals("password"))
This has been said many times, but I'll say it again, when comparing Strings in java, if you want to know if they point to the same reference use the == operator. if you want to check if they are equal in value use .equals("somestringhere") In your case use passwordinput.equals("password")
Since, in Java the line:
String s; declares a reference to a String object, unlike C++, which may declare an object of String.
So, the line if (passwordinput == "password") compares the reference of "password" and reference of passwordinput, the result will be false.
So, use if(passwordinput.equals("password"), which compares the object referenced by passwordinput with "password"
Trying to write a program that asks the user if they want instructions. If the user enters maybe the console responds with "please enter a yes or no answer" and repeats the question.
I'm having difficulty listing the method parameters for the method askYesNoQuestion. Are the parameters simply String yes, String no? I am also stuck on how do I make the program repeat the question after someone enters maybe? Does my code look generally correct for what I'm trying to do?
import acm.program.*;
public class Instructions extends ConsoleProgram{
public void run(){
String answer = readLine("Would you like instructions? : ")
{
if (answer.equals("maybe")) {
println ("Please enter a yes or no answer.");
}
}
}
private boolean askYesNoQuestion(String yes, String no ){
if (askYesNoQuestoin ("would you like instructions? "))
if (answer.equals("yes")) {
return yes;
} else {
if (answer.equals("no"))
return no;
}
}
Up to you how you do it, but really you are trying to convert a user's string input to something a bit easier for Java to work with.
I'd suggest askYesNoQuestion() would take the question to ask and then return true for yes and false for no. If you really want to handle "maybe" then use and int (or better yet an enum) to handle the response.
boolean askYesNoQuestion(String question)
{
while(true) {
// print the question
// get the answer
// if answer.equals("yes") return true
// if answer.equals("no") return false
// any other answer asks the question again
}
return false;
}
// call looks like
if (askYesNoQuestion("Do you want instructions?")) {
// do instructions
}
// Do the rest of the app.
//
Firstly, pass the question, not the answer (you don't know the answer yet; you only know the question), so your method should look like:
private boolean askYesNoQuestion(String question)
next, loop until you get a yes or a no response:
private boolean askYesNoQuestion(String question) {
println (question);
while (true) {
String answer = // read answer
if (!answer.equalsIgnoreCase("yes") && !answer.equalsIgnoreCase("no")) {
println ("Please enter a yes or no answer.");
} else {
return answer.equalsIgnoreCase("yes");
}
}
}
If you are using Java 7, the Switch statement now supports Strings.
I mean:
switch(inputString){
case "yes": /*do something */ break;
case "no": /*do something */ break;
case "maybe": /*do something */ break;
default: /*do something */ break;
}
So based on your requirement, you can write corresponding cases. For instance, you can display the message "enter yes or no" if user inputs "maybe" or something other than "yes" or "no" (using case "maybe" and default). Ideally, "maybe" is not required. the default case is used to handle this.
You can enclose this in a do-while loop and based on your condition, choose to continue or break
I don't know about your readline method, but I assume it's valid. So your run method should be :
public String run(){
while(true) {
String answer = readLine("Would you like instruction?: ");
if (answer.equals("maybe") {
System.out.println("Please enter a yes or no answer");
}
else {
return answer;
}
}
}
So, when this method is run, it will loop until the user doesn't type "maybe" (and hope they will type yes or no).
Well...there's a lot going on here. Don't feel bad about this, but it wouldn't work in this state - the compiler would throw a lot of stuff at you. Let's look at it step by step.
Before we look at syntax, let's look at program flow. What do we want to do? From your description you want to accomplish the following:
Have a user respond to a question for instructions.
If they reply with yes, then give them the instructions and exit.
If they reply with no, then exit.
If they reply with maybe, clarify that they should only have a yes or no answer, then ask your question again.
Now, we can look at syntax to accomplish this. In general, we will need a way to capture the user's response, and use that to decide what to do next. readLine() isn't what you're going to use (since that method doesn't exist); you'll want to use Scanner. The documentation in the API should be enough to get you started.
Next, now that we have the input, we need a way to repeat if the user doesn't answer yes or no. You have a choice - either a while loop or a do...while loop will work. We would have to check whether or not our condition is met, and if it isn't, we keep going.
Third, the string "yes" is different from "Yes" and "YeS" and "YEs". Case matters with strings, so the idea to compare them would be to equalsIgnoreCase().
Fourth, the method being created should only take in a single parameter - what the response is. You don't know what that will be until you actually do work on it - which is an if else-if else-if else statement. I see no reason for that method to call itself.
Finally, you don't call the method anywhere in run! You have to do that or it won't really matter what that method does; as long as it's syntactically correct, Java will happily ignore it if it's never called.
thanks for reading this. I'm creating just a simple, generic version of blackjack using java. Everything else works completely fine, except when it asks you "hit or pass" and you type pass, you must type it twice for it to reconize it, and I cant seem to find out why. Heres my code on pastebin to make it easier to read: http://pastebin.com/GF7Rzusx
Relevant code from pastebin:
public void ask()
{
System.out.println("Hit or Pass?");
if (in.next().equalsIgnoreCase("Hit"))
{
hit();
}
if (in.next().equalsIgnoreCase("Pass"))
{
pass();
}
}
If the entered word is "Pass" it is read from standard input and then lost, it is not stored. It must be stored for it to be available again in the subsequent check:
String input = in.next();
if (input.equalsIgnoreCase("Hit"))
{
hit();
}
else if (input.equalsIgnoreCase("Pass"))
{
pass();
}
Surely you want:
public void ask()
{
System.out.println("Hit or Pass?");
String answer = in.next();
if (answer.equalsIgnoreCase("Hit"))
{
hit();
} else if (answer.equalsIgnoreCase("Pass"))
{
pass();
}
}
Each time you call in.next() it throws away the previous input and expects another token (input).
Example
Imagine what would happen if you had:
System.out.println(in.next());
System.out.println(in.next());
What would it expect as input and what would it output?
Main differences in code
Note that there are two differences in the new code:
You only call in.next() once and so only need one input, which is stored as answer.
You only check whether the answer is "Pass" if it wasn't already "Hit".
See Java Scanner.next documentation.
On row 112 you do:
in.next()
This will read one string token. So if you write pass, this function will return "pass".
The problem is that you do not save this value. Instead, you run in.next() again on row 116, which will require you to write pass yet again.
Instead you would like to store the string returned from in.next() on line 112.
It is because of the way the ask() method is structured. Since you have two if statements, in.next() gets called once when checking if the response is "hit", then a second time when checking for "pass". When you enter "pass", the first if statement calls next(), which returns "pass" and checks if that is equal to "hit", then moves on. Then when the second if statement calls next(), there is no next entry to return, so you have to enter "pass" again. This works when you enter "hit", however, since that is the first case checked.
Refactoring so ask only makes one call to next() should solve the problem.