Problem solved.
I have two methods in my class.
private void retrieveDetails(){
List<String> details = File.getCredentials();
username = details.get(0);
pw = details.get(1);
}
private void checkCredentials() throws IOException {
retrieveDetails();
System.out.println("\nPlease enter USERNAME: ");
String usersName = scan.next();
System.out.println("\nPlease enter PASSWORD: ");
String usersPW = scan.next();
System.out.println("\nEntered details: " + usersName + ", " + usersPW);
System.out.println("\nSystems details: " + userName + ", " + pw);
if (usersName.equals(username) && usersPW.equals(pw)) {
doWork();
} else {
System.out.println("Incorrect credentials");
}
}
I thought I came up with a solution by moving the following up to where my strings are initialized.
List<String> creds = File.getCredentials();
I created a System.out statement to check if the details coming from retrieveDetails() match those entered by the users. They do match - but when the system goes to the else clause instead of executing doWork();
If what is printed is the same then try trimming before comparing. E.g.:
if (usersName.trim().equals(username.trim()) && usersPW.trim().equals(pw.trim())) {
When i have similar problem i do this simple trick:
Print the size of the strings you are comparing because sometimes you have characters like \n or \r which are not visible when you print the string.
First of all, it seems like you have a typo in sysout statement below.
System.out.println("\nEntered details: " + usersName + ", " + usersPW);
System.out.println("\nSystems details: " + userName + ", " + pw); //Should be username
Secondly, you might wanna trim the strings for better string comparison.
Sometimes strings read from file or console can contain unwanted and hard-to-catch empty strings like spaces and tabs. These can be removed by calling .trim() method on strings.
Thus, try using the following code instead:
if (usersName.trim().equals(username.trim()) && usersPW.trim().equals(pw.trim())) {
}
usersName.equals(username) && usersPW.equals(pw).
I have faced these problem also, These kind of equality always tricky, Try to trim the strings that you are going to compare, as well as if you can compare these strings based on their length.
if (usersName.trim().equalsIgnoreCase(username.trim()) && usersPW.trim().equalsIgnoreCase(pw.trim()))
or
if (usersName.trim().length()==username.trim().length && usersPW.trim().length()==pw.trim().length))
Related
I am trying to compare the below messages through java-selenium.But the lines are changing in the actual message during execution.Please let me know how to handle it.
Ex:
String expMsg="Line1.\n"
+ "Line2\n"
+ "Line3\n"
+ "Line4\n"
+ Line5\n" + "\n"
+ "Line6."
String actMsg="Line1.\n"
+ "Line3\n"
+ "Line2\n"
+ "Line5\n"
+ Line4\n" + "\n"
+ "Line6."
I tried the following but it is failing :
if(actMsg.contains(expMsg){
System.out.println("both the messages are same")
}
Please let me know how to resolve this.
Convert your Strings to Streams
Arrays.stream(actMsg.split("\n"));
And then compare streams
Here is how I solved your example:
List<String> expMsg = Arrays.asList("Line1", "Line2", "Line3", "Line4", "Line5", "Line6");
String actMsg = "Line1.\n"
+ "Line3\n"
+ "Line2\n"
+ "Line5\n"
+ "Line4\n" + "\n"
+ "Line6.";
boolean containsAll = expMsg.stream()
//select only elements which are in actMsg
.filter(actMsg::contains) //e -> actMsg.contains(e)
//all strings from expMsg should be present
.count() == expMsg.size();
System.out.println(containsAll);
Split all lines from expMsg and check if all line are in actMsg.
AS per my understanding, the order of actualMessage does not matter, you just need to check all the expectedMessage is present in the actualMessage ? In this case save each line in a separate variable/array then verify each expectedMessage is present in actual using contains.
`
for(i=1, i<6, i++) {
if(actMsg.contains(expMsg+i){
System.out.println("both the messages are same")
}else
System.out.println("both the messages are not same")
}
`
Let me know if this works
I have a really big program that needs to check what character is typed this is just a part of the broken part. So it worked when I had it logging each character typed. But when I try to add each character to the string so when they type the word hi it looks like this:
hi
and NOT
h
i
No matter what i try it either gives me the first value typed and doesnt add each character to the string I also want it to print out the string every 5 seconds im not sure if I did that right either but it might be correct.
String log = " ";
if(event.getVirtualKeyCode() == GlobalKeyEvent.VK_SPACE){
log = log + "";
}
if(event.getVirtualKeyCode() == GlobalKeyEvent.VK_BACK){
log = log + "[BACKSPACE]";
}
String timestamp = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss").format(Calendar.getInstance().getTime());
while(true){
try {
Thread.sleep(5000);
System.out.println("[" + timestamp + "]" + log);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
Try to declare a new string:
String log = new String(" ");
I have a text file that holds data like this:
Jones,Mary,903452
4342,2.5,A
3311,4,B+
I'm using Scanner to read the file. This is my code:
while(reader.hasNextLine())
{
reader.useDelimiter(",");
String lastN = reader.next();
String firstN = reader.next();
String id = reader.nextLine();
String course1 = reader.next();
double credits = reader.nextDouble();
String grade = reader.nextLine();
}
But when I print the line on the console, the , on the last part of the line doesn't get delimited and it prints like this:
Jones, Mary, ,903452
4342, 2.5, ,A
6.5, ,3.569
My toString method on my class:
public String toString() {
return lastName + ", " + firstName + ", " + idNo + "\n"
+ courseOne + ", " + credits + ", " + grade;
I'm searched around for a solution. I tried reader.useDelimiter("[,]") and reader.useDelimiter(",|,") but still gives me the same output. How can I fix this?
From the Scanner's documentation:
This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
(Emphasis mine) This means that the whole rest of the line is returned, including delimiters. Setting id to reader.next() wouldn't work because it sucks up everything until the next delimiter. A better solution would be to make it accept line breaks as a delimiter, like so:
reader.useDelimiter("[,\n]");
My user inputs work fine, my problem is I want an if statement that will say are both inputs equal?, but I get the attached error.
I need the code to be: if cork is entered in batman and robin?. This is what I tried:
System.out.println("From " + batman);
System.out.println("To " + Robin);
if(batman.equals("Cork") + Robin.equals("Cork") {
} else {
System.err.println("");
}
that here:
if(batman.equals("Cork") + Robin.equals("Cork") {
makes no sense because you are doing something like concatenating true with true or similar...
you have to do instead:
if(batman.equals("Cork") && Robin.equals("Cork") {
Your code should look like this :
System.out.println("From " + batman);
System.out.println("To " + Robin);
if(batman.equals("Cork") && Robin.equals("Cork")) {
// Statements
} else {
System.err.println("");
}
You should simply use && when requiring more then one test in an if statement.
+ doesn't work in such cases it simply concatenates values. Hope it helps :)
Weird problem. I run this (very elementary) procedure to find a username and password in a file, and the program should compare the password entered to the password saved. Every time, however, i get a strange String index out of range: -1 exception. I've suffered a similar problem before, however this time the indexOf('.') call is returning -1; which it doesn't like. Why is indexOf() returning -1 if it causes an error? Here's the source:
public String loginToClient() throws FileNotFoundException, IOException {
//decryptUsers();
int tries;
tries = 5;
while (tries > 0) {
System.out.println("LOGIN");
String usnm = c.readLine("Username: ");
char [] passwd = c.readPassword("Password: ");
users = new FileInputStream("users.fra");
DataInputStream dis = new DataInputStream(users);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String logindat = br.readLine();
System.out.println(logindat);
if (logindat.contains(usnm) == null) {
System.err.println("Username not recognised, please try another or create user.");
usnm = "INV";
return usnm;
}
else {
int startUsnm = logindat.indexOf(usnm);
System.out.println("startUsnm: " + startUsnm);
String logdat = logindat.substring(startUsnm, logindat.indexOf("."));
System.out.println("logdat: " + logdat);
int endUsnm = logdat.indexOf(':');
System.out.println("endUsnm: " + endUsnm);
int usnmend = endUsnm - 1;
System.out.println("usnmend: " + usnmend);
int startPass = endUsnm + 1;
System.out.println("startPass: " + startPass);
int endPass = logdat.indexOf('.');
System.out.println("endPass: " + endPass);
String Usnm = logdat.substring(0, usnmend);
System.out.println("Usnm: " + Usnm);
int passend = endPass - 1;
System.out.println("passend: " + passend);
String Pass = logdat.substring(startPass, passend);
System.out.println("Pass: " + Pass);
char [] Passwd = Pass.toCharArray();
if (usnm.equals(Usnm)) {
if (Arrays.equals(passwd,Passwd)) {
System.out.println ("Logged in. Welcome, " + usnm + ".");
String data = "LOGIN: " + usnm;
printLog(data);
//encryptUsers();
return usnm;
}
else {
System.out.println ("Incorrect password, please try again.");
String data = "PASWFAIL: " + usnm;
printLog(data);
tries -= 1;
}
}
else {
System.out.println ("Username not recognised.");
printLog("USNAMFAIL");
usnm = "INV";
return usnm;
//encrytUsers();
}
}
}
//encryptUsers();
System.exit(2);
return usnm;
}
And here's some input/output:
Startup initiated.
Logfile exists.
Users file exists.
New user? n
ELSE
LOGIN
Username: rik
Password:
rik:55.
startUsnm: 0
endUsnm: 3
startPass: 4
endPass: -1
Usnm: rik
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -5
at java.lang.String.substring(String.java:1949)
at client0_0_2.loginToClient(client0_0_2.java:103)
at client0_0_2.general(client0_0_2.java:209)
at client0_0_2.<init>(client0_0_2.java:221)
at client0_0_2.main(client0_0_2.java:228)
EDIT : SOLUTION FOUND!
For some reason, indexOf() does not want to find a '.'- when replaced with a hyphen('-'), however, it runs perfectly, seemingly!
I think the error is in this line:
String Pass = logdat.substring(startPass, passend);
For some reason (you'll have to determine why), you compute passend by searching for . in the string. If . isn't present, indexOf returns -1 as a sentinel. This isn't the line that causes the exception, though. I think it's the above line, since if you try to compute a substring ending at passend when passend is -1, you would get the above error.
Try determining why your string doesn't contain a . in it.
Hope this helps!
When indexOf() returns -1, it means that the value couldn't be found in the String. So, in this case, you're searching a String for '.' which doesn't exist in the String.
I would recommend that you always check the values of indexOf() after the call, and handle the -1 properly. For many cases, its probably sufficient to set it to either 0 or string.length(), depending on how you will use it later in your code.
Regardless, if you're expecting a '.' to exist and there isn't one, you'll need to debug through your code to find out what the value is, and where the '.' is missing.
indexOf() returns -1 if the specified string can't be found.
The problem is in the Line:
String Pass = logdat.substring(startPass, passend);
because of negative index.