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.
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.
So, in Java, I want the user to provide either Y or N to my prompt. Lets say (dream sequence begins with swirly sounds) I am currently using this code:
String output = "";
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("[P]ast or [F]uture?");
String input = scan.nextLine().toLowerCase();
if (input.equals("p") || input.equals("f")){
output = input;
break;
} else {
System.out.println("Please provide a valid answer.");
}
}
There has got to be a more efficient way of doing this. Can anyone enlighten me?
There is no way you can force the user to type in something. You'll have to sanitize the data and throw an error at the user when he types in something wrong, much like your code is doing now.
Use a GUI library such as Swing or JavaFX and only allow the allowable input. For instance if this were Swing and the user were entering input into a JTextField, you could add a DocumentFilter to the JTextField's document, preventing the user from entering anything but 'y' or 'n'.
Have you tried hasNext(String pattern) to validate that the next token consists of your desired pattern?
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
http://www.tutorialspoint.com/java/util/scanner_hasnext_pattern.htm
while (!sc.hasNext("[A-Za-z]+")) {
System.out.println("Error");
sc.next();
}
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;
}
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.
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"),"");