I am writing a program that has 4 usernames and 4 passwords. If the user enters the right name with the right password, it then outputs "Welcome!". It only gives 2 tries. This is what I wrote, but when I run this code it doesn't end. It keeps asking for username non-stop. Can someone help me, guide on what I'm doing wrong, or what I am missing? Thanks.
public class password
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int limit = 2;
int count = 0;
String[] user = {"Diana","Jasmin","Jimmy","Ross"};
String[] passwords = {"Flower01","Cheer02","Reading03","Math04"};
while (true)
{
System.out.print("Enter Username: ");
String [] name = input.nextLine();
if(user.equals(name))
{
while (count < user.length)
{
System.out.print("Enter password: ");
String [] word = input.nextLine();
if (word.equals(passwords))
{
System.out.println("Welcome!");
}
else
{
System.out.print("Sorry can not be found");
count++;
}
}
}
}
}
}
while(true) {...}
is a loop that never ends, you should put you condition at the place of the true.
You can for example add a second count for the first loop (here you want 4 I suppose).
String [] name = input.nextLine();
This line should not compile because you are assigning a string to an array.
Here is simple cut of your code that works. Couple of things
Start Class name in capital.
You were reading input as Arraywhich should really fail at compile time really.
You were not updating the count or displaying any thing if username is wrong.
Use Printlnto get new line after print.
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int limit = 2;
int count = 0;
String[] user = {"Diana","Jasmin","Jimmy","Ross"};
String[] passwords = {"Flower01","Cheer02","Reading03","Math04"};
while (count <4)
{
System.out.print("Enter Username: ");
String name = input.nextLine();
if(user.equals(name))
{
while (count < user.length)
{
System.out.print("Enter password: ");
String word = input.nextLine();
if (word.equals(passwords))
{
System.out.println("Welcome!");
}
else
{
System.out.println("Sorry can not be found");
count++;
}
}
}
else
{
System.out.println("Sorry can not be found");
count++;
}
}
}
}
You have a while true in your code. What you probably want to do, is to replace the while true with count and limit condition. Most of your code is already in place, you'll only need to replace the while true.
I'm also not sure why you have the second loop, which iterates over the users, sort of. I think what you can better do is replace the 2 arrays with a simple HashMap, something like this:
Map users = new HashMap();
users.put("name1", "password1");
users.put("name2", "password2");
users.put("name3", "password3");
users.put("name4", "password4");
And then, based on the username, you do a users.get(username) to get the password. Then, compare the password with the password the user typed. If it's correct, say welcome, if it's not correct, say error, and increment the counter. Then, if the counter is bigger than the max, stop the program. Hope that helps!
Related
public class Test1 {
public static void main(String[] args) {
System.out.println("Give me a word: ");
Scanner console = new Scanner(System.in);
ArrayList<String> arr = new ArrayList<>();
boolean found = true;
while (console.hasNextLine() && found) {
String line = console.nextLine();
if (line.equals("")) {
found = false;
} else {
arr.add(line);
}
}
System.out.println("You said: ");
for (int index = 0; index < arr.size(); index++) {
System.out.println(arr.get(index));
}
}
}
I'd like to print what user typed in whenever the user types enter twice, however this requires three enters to be inputted for some reason. When I remove the console.hasNextLine statement in while loop's condition, it works perfectly fine. Why is this the case?
console.hasNextLine() blocks application flow and waits for input to be received.
1st enter - word is found and found remains == true
2nd enter - word is not found and found is set to == false
3rd enter - is required because your booleans are evaluated in order which they are arranged. so first it'll call console.hasNextLine() and allow user to provide input. THEN it'll check if found == true/false which would == false and would break out of the loop.
an easy solution would be to rearrange your conditions to be
found && console.hasNextLine()
I have the below code that is not reading or infinitely looping when a user inputs text using System.in. If I hard code the text into the Scanner variable it works fine so I am not sure what is wrong with the System.in portion of this code. Any help is appreciated.
import java.util.Scanner; // needed to use the Scanner class
public class HW2 {
static Scanner in = new Scanner(System.in);
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
while (in.hasNext()){
String word = in.next();
if (word.equals("the")){
the++;
}
else if( word.equals("and")){
and ++;
}
else if (word.equals("is")){
is++;
}
else if (word.equals("was")){
was++;
}
else noword++;
}
System.out.println("The number of occurrences of the was"+ the);
System.out.println("The number of occurrences of and was"+ and);
System.out.println("The number of occurrences of is was"+ is);
System.out.println("The number of occurrences of was was"+ was);
}
}
As has been mentioned, a Scanner attached to System.in will block while looking for more input. One way to approach this would be to read a single line in from the scanner, tokenize it, and then loop through the words that way. That would look something like this:
//...
String line = in.nextLine(); // Scanner will block waiting for user to hit enter
for (String word : line.split(" ")){
if (word.equals("the")) {
the++;
}
//...
You can always substitute one loop structure (for, while, do-while) for another. They all do the same thing, just with different syntax to make one a bit simpler to use than others depending on the circumstances. So if you want to use a while loop, you can do something like this:
// ...
String line = in.nextLine();
String[] tokens = line.split(" ");
int i = 0;
while (i < tokens.length){
String word = tokens[i];
if (word.equals("the")) {
the++;
}
// ...
i++;
} // end of the while loop
However, I'm of the opinion that a for loop is cleaner in the case of looping over a known set of data. While loops are better when you have an unknown dataset, but a known exit condition.
As System.in is always available while the program is running unless you close it. It will never exit the while loop. So you could add else if (word.equals("exit")) { break; }. This way, whenever you type 'exit' it will close the while loop and execute the code AFTER the while loop.
Depends, do you want to just read 1 line of text and then count the words individually?
Because is you want only one line you could take the input string using the Scanner library and split the string into individual words and apply the if-statement then. Something like:
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
String input = in.nextLine();
String words[] = input.split(" ");
for (String s : words) {
if (s.equals("the")){
the++;
} else if( s.equals("and")){
and++;
} else if (s.equals("is")){
is++;
} else if (s.equals("was")){
was++;
} else {
noword++;
}
}
System.out.println("The number of occurrences of the was: "+ the);
System.out.println("The number of occurrences of and was: "+ and);
System.out.println("The number of occurrences of is was: "+ is);
System.out.println("The number of occurrences of was was: "+ was);
}
This way you won't need a while loop at all. So it's more processor and memory efficient.
At the start of the code the user determines a number of keywords and the keyword strings themselves, they place this into an array. Lets say the user says 3 keywords and they are "music", "sports" and "memes". After all this, say the user inputs in the program "I like sports". I simply want the program to respond with "Let's talk about sports" after recognising that the user said sports which is in the array that the user has essentially created.
I want to reference a string the user has predetermined then print it along with a message
I can see the potential of this working using for loops and going through every article until you find a match, I haven't done much work with booleans yet so I just need some assistance punching out the code then learning from it
this all has to happen inside a while loop so when that's done they can use a different keyword and get the same boring response
thanks
note: I don't actually have any of this code I want in my program yet, this code is just to show you kind of how it fits into the greater scheme of things.
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
String kwArray[];
String UserMessage;
String Target = "";
int numKw = 0;
Scanner input = new Scanner(System.in);
System.out.println("How many keywords do you want?");
numKw = input.nextInt();
kwArray = new String[numKw];
System.out.print(System.lineSeparator());
input.nextLine();
for (int i = 0; i < numKw; i++) {
System.out.println("Enter keyword " + (i + 1) + ": ");
kwArray[i] = input.nextLine();// Read another string
}
for (int i = 0; i < numKw; i++) {
kwArray[i] = kwArray[i].toLowerCase();
}
int x = 0;
while (x == 0) {
System.out.println("Hey I'm a chatbot! Why don't you say something to me!");
System.out.println("These are the keywords you gave me");
for (String i : kwArray) {
System.out.print(i);
System.out.print(", ");
}
System.out.print(System.lineSeparator());
System.out.println("Or you can terminate the program by typing goodbye");
UserMessage = input.nextLine();
// Gives the user opportunity to type in their desired message
UserMessage = UserMessage.toLowerCase();
if (UserMessage.contains("?")) {
System.out.println("I will be asking the questions!");
}
if (UserMessage.contains("goodbye")) {
x = 1;
}
}
input.close();
}
}
If I am getting the question right, you want to check whether an element exists in the submitted keywords and want to reference it back if you further processing.
For this, instead of an array you could use a HashSet which can check the existence any element in O(1).
Updated the code, but I still feel your query is the same what I understood, putting the exact example of your use case below:
Scanner input = new Scanner(System.in);
Set<String> set = new HashSet<String>();
int keywords = input.nextInt();
for (int i=0; i<keywords; i++) {
//add to set set like:
set.add(input.readLine());
}
String userComment = input.readLine();
String[] userCommentWords = userComment.split(" ");
//you can iterate over the words in comment and check it in the set
for (int i=0; i<userCommentWords.length; i++) {
String word = userCommentWords[i];
if (set.contains(word)) {
System.out.println("Let's talk about "+word);
}
}
I'm still relatively new to Java and wanted to try out some new stuff related to strings. I tried to write a code for the user to enter a password between 4-12 characters, and so far it worked fine. But during the process, I had to make little fixes here and there, and honestly it does look pretty messy, like a puzzle where all pieces fit but don't make one whole picture. I want my code to be something more "optimized" so I can have an idea of how codes like this one works, you know, just for future reference. So any help appreciated, please take a look at my code and see if there's anything that can be improved. Thanks!
import static java.lang.System.*;
import java.util.Scanner;
public class PasswordWithLimit {
public static void main (String[] args){
Scanner scan = new Scanner (in);
out.print("Enter your password(4-12 characters): ");
String pass = scan.nextLine () + " ";
char check = pass.charAt (11);
if (pass.indexOf (" ") == 3){
out.println("Please enter a valid password: ");
}
if (Character.isSpaceChar(check) || Character.isWhitespace(check)){
out.println("Your password is " + pass);
}
else{
out.println("Please enter a valid password");
}
}
}
I would recommend using the String's length property. This example prompts the user to enter their password and continues asking them until they have entered something which meets the requirements.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter your password (4 to 12 characters)"); // Prompt the user
boolean valid = false;
while (!valid) {
String password = in.nextLine();
if (password.length() > 3 && password.length() < 13) {
valid = true; // Length between 4 and 12, we can stop asking.
System.out.println("Your password is " + password);
} else {
System.out.print("Please enter a valid password: "); // Invalid length, ask again.
}
}
in.close();
}
The title is deceiving however I didn't really know how to ask this.
I am playing around with java. This is my code:
package zodiac;
import java.util.Scanner;
public class Zodiac {
public static void main(String[] args) {
Scanner username = new Scanner(System.in);
String uname;
System.out.println("Please enter your username: ");
uname = username.nextLine();
boolean test = (uname.length() <= 3);
int trip = 0;
while (trip == 0) {
trip++;
if (test) {
trip = 0;
System.out.println("Sorry username is too short try again");
uname = username.next();
}
else {
System.out.println("Welcome Mr/Mrs: " + uname);
}
}
}
}
what i'm trying to do is prompt the user to enter their username and once they do check if the name is less than or equal to 3 make them type the username again, if the username if more than 3 chars print welcome mr/mrs blablabla
at the moment if the username if more than 3 chars it prints out the welcome message, however if you enter 3 or less chars it tells you to enter the username again and if you type a username with more than 3 chars afterwords it keeps telling the user that the password is too short.
How can i fix this. I have just recently started studying java at university however my teachers lack motivation to teach so i have to result to the internet, thank you.
There are two things that you might want to think about in your code:
don't use an integer to stop looping if a boolean would be sufficient
a do-while loop might be more appropriate for your case (you don't have to rewrite code that way!
Now to your question: You are not checking the required minimum length of the inserted string in your loop again! This code might help you to understand all of the points i mentioned:
public static void main(String[] args) {
Scanner username = new Scanner(System.in);
String uname;
System.out.println("Please enter your username: ");
boolean tooShort = true;
do {
uname = username.next();
if (uname.length() <= 3)
System.out.println("Sorry username is too short try again");
else {
System.out.println("Welcome Mr/Mrs: " + uname);
tooShort = false;
}
} while (tooShort);
username.close();
}
insert boolean test = (uname.length() <= 3) in your loop