Trying to get program to repeat - java

The program checks to see if the email address entered contains a # and a .edu
if it doesn't it needs to go back through the steps, I think I can use a do-while,but I haven't got one to work yet, how would I nest my if-else statements in a do-while? Thanks!
if (UserEmail.contains("#")) {
if (UserEmail.contains(".edu")){
System.out.print("Please create a password: ");
PassWord = kb.nextLine();
System.out.println(UserEmail.replaceAll("#\\S+?\\.edu\\b", ""));
System.out.print("Your password is " + PassWord);
} else {
System.out.print("email is not valid Please, try again.")
} else {
System.out.print("email is not valid Please, try again.");
// at this point it should repeat and ask for the email again
}
}

Define method isValid(String email, String password,... some more params) aand put all your check logic in the method.
Write something like this
while (!isValid(the params)) {
//ask all the credentials
}

to simplify your if-else code consider using
if (UserEmail.contains("#") && UserEmail.contains(".edu")) {
.
.
}
this can be wrappped in a do - while
do {
if (UserEmail.contains("#") && UserEmail.contains(".edu")) {
.
.
break;
}
System.out.print("email is not valid Please, try again.")
}
while (true);

You can simply add something like boolean correctEmail = false before your logic and at the beginning of your if statements, you write while(!correctEmail) {
At the end of your password-creation you set correctEmail to true and you're ready to go.

It is pretty straight forward.
bool trigger = (true/false);
do {
if (...) {
if (...){...}
else if (...) {...}
else {
print out retry statement;
trigger = false;
}
}
}
while (trigger == true);
Don't forget a semicolon at the end.

Related

How i can update this Setlist of users?

I need some help guys. I'm making a chat who read an XML each 10 sec aprox (yeah the database is the XML, congrats my teacher, we can't change database format xDD)
So on, my question now i create the function, replace the messages is easy, if the xml messages are more than RAM one, then i clear the ram and then add all messages again, but i can't do that to users, i don't know why but i think equals or something is broken(? i don't know pls help me my brain is about to break!
if (temp.getList().size() > roomList.getList().size()) {
for (Room room_xml : temp.getList()) {
if (roomList.addRoom(room_xml)) {
System.out.println("A room was loaded");
}
}
} else {
for (Room room_xml : temp.getList()) {
for (Room room_ram : roomList.getList()) {
if (room_ram.equals(room_xml)) {
if (room_ram.getMessageList().size() < room_xml.getMessageList().size()) {
room_ram.getMessageList().clear();
room_ram.getMessageList().addAll(room_xml.getMessageList());
}
Set<User> us_xml = room_xml.getUserList();
for(User u_xml: us_xml){
for(User u_ram: room_ram.getUserList()){
if(room_ram.getUserList().add(u_xml)){
System.out.println("User was added(?");
}
}
}
/*for (User u_xml : room_xml.getUserList()) {
if(room_ram.getUserList().add(u_xml)){
System.out.println("User was added(?");
}else{
break;
}
}*/
I share my proyect on github if u need more info about that : https://github.com/Varo95/ChaTerra
This code is on RoomListDAO.java
PD: I put print but i use javafx xd
I got another idea, like declaring actual_user on roomdao and check on xml is on the list to add one....but doesn't seems to work :(
I already resolve it, thanks any way, i already do this and seems to work:
RoomList temp = load();
if (temp.getList().size() > roomList.getList().size()) {
for (Room room_xml : temp.getList()) {
if (roomList.addRoom(room_xml)) {
System.out.println("Room was loaded on RAM");
}
}
} else {
for (Room room_xml : temp.getList()) {
for (Room room_ram : roomList.getList()) {
if (room_ram.equals(room_xml)) {
if (room_ram.getMessageList().size() < room_xml.getMessageList().size()) {
room_ram.getMessageList().clear();
room_ram.getMessageList().addAll(room_xml.getMessageList());
}
room_ram.getUserList().clear();
room_ram.getUserList().addAll(room_xml.getUserList());
}
break;
}
}
}
saveFile(roomList);
And saving it too when user left the room or join but i need to make some little fixes more hahahaha well now i feel good with myself

How do I Check search keyword in the URL

I am a beginner in Selenium. I wanted to know how I can verify the URL against the keyword I entered in the search bar.
The search page url is https://catalog-mytest.com/search?
When I entered redcar in the search bar and hit enter, the url becomes https://catalog-mytest.com/search?keywords=redcar
Could you guide me on how to write a piece of code that would verify the URL with the keywords? thank you.
There can be two approaches-
Approach-1:
String url = Driver.getCurrentUrl();
boolean passed = url.contains("your keyword here");
if (passed) {
System.out.println("Test Passed");
} else {
System.out.println("Test Failed");
Assert.fail("This message will be printed in stacktrace if the assertion fails.");
}
This is the simplest way of doing this.
Approach-2:
String keyword = Driver.getCurrentUrl().split("?")[1].split("=")[1];
boolean passed = keyword.equals("your keyword here");
if (passed) {
System.out.println("Test Passed");
} else {
System.out.println("Test Failed");
Assert.fail("This message will be printed in stacktrace if the assertion fails.");
}
This approach can be error prone, if the URL does not always contain
?, = in it then the test can fail with
ArrayIndexOutOfBoundsException

Java Minecraft Plugin Issue - Not responding to if statement?

So I'm making a simple code redemption plugin for a Minecraft server. What's weird is when I type /redeem (the valid code), nothing happens, although it's supposed to... The valid code is the a code entered into the plugins configuration by the user.
Here's my code...
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
//Assigns the commands chosen in config to strings
String commandChosen1 = this.getConfig().getString("Command for code 1");
String commandChosen2 = this.getConfig().getString("Command for code 2");
String commandChosen3 = this.getConfig().getString("Command for code 3");
//Assigns the codes to strings
String validCode1 = this.getConfig().getString("Valid Code 1");
String validCode2 = this.getConfig().getString("Valid Code 2");
String validCode3 = this.getConfig().getString("Valid Code 3");
//If the redeem command is sent from a player
if(cmd.getName().equalsIgnoreCase("redeem") && sender instanceof Player)
{
//Casts the sender to a new player.
Player player = (Player) sender;
//Creates object hasUSed to store whether or not the player has already redeemed a code
Object hasUsed = this.getConfig().get(player.getName());
//Gives an error message of the arguments don't equal 1.
if(args.length != 1)
{
player.sendMessage(ChatColor.DARK_RED + "Please enter a valid promo code. Find them on our twitter!");
}
if(args.length == 1)
{
//If the player hasn't used the code yet and the arguments given are equal to a code then give them the reward...
if(args[0] == validCode1 && hasUsed == null)
{
this.getConfig().set(player.getName(), 1);
player.sendMessage(ChatColor.GREEN + "Promo code successfully entered!");
if(commandChosen1 == "xp")
{
Bukkit.dispatchCommand(player, commandChosen1 + getConfig().getString("XP Given") + "L" + " " + player.getName());
}
}
}
return true;
}
return false;
}
The problem occurs on "if (args[0] == validCode1 && hasUsed == null)". The code that's supposed to happen if both those things check out, doesn't happen and I have no clue why.
Make sure to use equals() when comparing Strings. Using commandChosen1 == "xp" compares string references not values; use commandChosen1.equals("xp") or if you prefer "xp".equals(commandChosen1).
Also,
While it is possible to use a this.getConfig().getString()with a key value that contains spaces, it can make configuration files hard to read and cluttered. Whenever I design plugins I'll design my config.yml as such
VoteGUI:
message: 'hello'
and then run a this.getConfig().getString("VoteGUI.message");
For yours I'd suggest something like this
Promo-Codes:
validCode1: 'insert code here'
validCode2: 'insert code here'
validCode3: 'insert code here'
and then put this in your onCommand method:
String validCode1 = this.getConfig().getString("Promo-Codes.validCode1");
String validCode2 = this.getConfig().getString("Promo-Codes.validCode2");
String validCode3 = this.getConfig().getString("Promo-Codes.validCode3");
If this does not resolve the issue, copy and paste the exception being thrown from the console and I may be of further assistance

How to prevent/restrict blank values from being added to a mysql database in java?

I wanted to prevent my java program from accepting/inserting blank or "" value in the database. I already set columns username and password as not null though but it keeps on accepting blank or "" values.
heres a part my code for adding values into the DB:
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
try{
theQuery("insert into accounts (username,password) values ('"+user1.getText()+"', '"+pass1.getText()+"')");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Unable to add record to the database");
}
}
P.S. password is not hashed since this is for activity only.
try like this:
String str=user1.getText();
if ("".equals(str)){ //User have not entered anything.
JOptionPane.showMessageDialog(null,"Please enter your name.");
nameField.requestFocusInWindow();
//Do NOT loop here.
}
else {
//Do everything you need to do when the user have entered something
}
FYI You might also want to look at Apache Commons StringUtils for testing of null, empty, blank strings:
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html
It has lots of handy (nullsafe) methods like "isBlank", "isEmpty" etc
Replacing idioms like:
if (myString != null && myString != "")
With:
if (!StringUtils.isBlank(myString))

Checking if the username already exists in google's datastore using Java

EDIT: Alex Martelli Gave me a great answer which I changed only slightly in order to get working properly for me
The answer to this problem for me was
public boolean Login2(String usernamein, String passwordin) {
DatastoreService datastore = DatastoreServiceFactory
.getDatastoreService();
Filter usernamefilter = new FilterPredicate("username",
FilterOperator.EQUAL, usernamein);
Query validuserquery = new Query("Users").setFilter(usernamefilter)
.setKeysOnly();
Entity theUser = datastore.prepare(validuserquery).asSingleEntity();
if (theUser == null) {
System.out.println("Username not found");
return false;
}
return true;
}
End of EDIT
Original Post
Okay so I have spent the entire day trying to do this and have tried my best to research it but I can't do it! :(
I feel like there is probably and easy answer but I can't work it out, I feel like I have tried Everything! please please please help D:
I have a Login section of code on its own .jsp page called Index.jsp
String username = "";
String password = "";
try {
if (request.getParameter("usernamein") != null && request.getParameter("passwordin") != null) {
username = (request.getParameter("usernamein"));
password = request.getParameter("passwordin");
if(login.Login2(username, password)){
response.sendRedirect("Race.jsp");
System.out.println("go to next page");
} else {//need username/password
out.println("your username or password is incorrect");
}
}
} catch (Exception e) {
out.println("problem in getting u an p error =" + e);
}
Part way through that code is the line (login.Login2(username, password))
that code calls a method in a class using java use bean thingy
the method it calls is this:
public boolean Login2(String usernamein, String passwordin) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Filter usernamefilter = new FilterPredicate("username", FilterOperator.EQUAL, usernamein);
Query validuserquery = new Query("Users");
validuserquery.addProjection(new PropertyProjection("username", null));
System.out.println(validuserquery);
List<Entity> list = datastore.prepare(validuserquery).asList(FetchOptions.Builder.withLimit(100));
System.out.println(list);
for (Entity username : list){
System.out.println("username is equal to '"+username+"'");
if(username.equals(usernamein)){
return true;
}else
System.out.println("was not equal");
return false;
}
return false;
}
I'm trying to only go to the next page in the top code if the if statement is true, meaning that the username does exist, eventually I want it to only go to then next page if the username and password are both in the same entity i.e. the combination exists.
I hope you guys understand what i am trying to do and can help me
oh the System.out.println() for the username value outputs this:
username is equal to '<Entity [user("id")/Users(5910974510923776)]:
username = RawValue [value=[B#187c4d7]
>
'
If you need any more info just ask and i'll add it to the post :D ty
You would be best advised to query the datastore for just the username of interest...:
Query validuserquery = new Query("Users").
setFilter(new Query.FilterPredicate("username",
Query.FilterOperator.EQUAL,
usernamein)
).setKeysOnly();
Entity anyentity = datastore.prepare(validuserquery).asSingleEntity();
if(anyentity == null) {
System.out.println("was not equal");
return false;
}
return true;
This assumes there are no entities with duplicated username in your store (though you could deal with that by catching exception PreparedQuery.TooManyResultsException -- if that gets raised, it means you have more than one entity with that username, so that would be a return true case too:-).
The core idea is: getting every user entity and checking their usernames in your application code is really wasteful of resources (quite apart from the bugs in your code in this case) -- use queries to get only the relevant entity or entities, if any!-)
Try searching a bit more next time. It's not that hard, your issue was pretty easy. In any case :
Your query returns a full object, not just properties of your object. You need to do
entity.getProperty("username")
So that you see your property, not the full object.
More info here.

Categories

Resources