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.
Related
I have the following code to generate sequential Mac Addresses. The code works well if I statically define the string when creating the hextint. However, if I change the string to a variable, as seen below, I get an error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "6CDFFB6000000A
"
I'm sure I'm missing something simple here. Why is the string as a variable not converting? Any help is appreciated.
String macAddr = last_mac.getText();
// int qty = Integer.parseInt(label_qty.getText());
System.out.println("String to convert: " + macAddr);
// long hexint = Long.parseLong("6CDFFB60000000", 16);
long hexint = Long.parseLong(macAddr, 16);
System.out.println("String converted to Long:" +hexint);
System.out.println("10+ previous number:" + (10+hexint));
System.out.println("Convert back to hex: " + Long.toHexString(10+hexint).toUpperCase());
for(int i = 1; i < 10+1; i++){
System.out.println(i +" MAC: " + Long.toHexString(hexint + i).toUpperCase());
macAddr = Long.toHexString(hexint + i).toUpperCase();
}
Your text contains a trailing space. You should remove it by trim() method. Try the following code & it should work for you.
String macAddr = last_mac.getText().trim();
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(" ");
java.lang.NumberFormatException: For input string: ":"
What does this mean?
I get the above error if I run the code (below).I am a beginner here.
and..
stacktrace:[Ljava.lang.StackTraceElement;#e596c9
the code:
try
{
Class.forName("java.sql.DriverManager");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/bvdb","root","enter")
Statement stm=con.createStatement();
String m="-",t="-",w="-",th="--",f="-",st="--",s="-",runson;
if(jCheckBox1.isSelected()==true){
m="m";}
if(jCheckBox2.isSelected()==true){
t="t";}
if(jCheckBox3.isSelected()==true){
w="w";}
if(jCheckBox4.isSelected()==true){
th="th";}
if(jCheckBox5.isSelected()==true){
f="f";}
if(jCheckBox6.isSelected()==true){
st="st";}
if(jCheckBox7.isSelected()==true){
s="s";}
runson= m + t + w + th + f + st + s ;
int h1=Integer.valueOf(jTextField10.getText().substring(0,2)
int mins1=Integer.valueOf(jTextField10.getText().substring(3,5));
int h2=Integer.valueOf(jTextField12.getText().substring(0,2));
int mins2=Integer.valueOf(jTextField12.getText().substring(2,3));
Boolean x=jTextField10.getText().substring(2,3).equals(":");
Boolean y=jTextField12.getText().substring(2,3).equals(":");
String time1=jTextField10.getText().substring(0,2)+jTextField10.getText().substring (2,3)+jTextField10.getText().substring(3,5);
String time2=jTextField12.getText().substring(0,2)+jTextField12.getText().substring(2,3)+jTextField12.getText().substring(3,5);
String tfac1=jTextField13.getText();
String tfac2=jTextField14.getText();
String tfac3=jTextField15.getText();
String tfsl=jTextField16.getText();
if(Integer.valueOf(jTextField3.getText())==0){
tfac1="0";
if(Integer.valueOf(jTextField4.getText())==0){
tfac2="0";}
if(Integer.valueOf(jTextField5.getText())==0){
tfac3="0";}
if(Integer.valueOf(jTextField6.getText())==0){
tfsl="0";}
if(y==true&&x==true&&jTextField1.getText().trim().length()<=6&&jTextField2.getText().trim().length()<=30&&h1<=24&&h2<=24&&mins1<=59&&mins2<=59){
String q="INSERT INTO TRAININFO VALUE ("+jTextField1.getText()+",'"+jTextField2.getText()+"','"+jTextField9.getText()+"','"+time1+"','"+jTextField11.getText()+"','"+time2+"','"+runson+"',"+tfac1+","+tfac2+ ","+tfac3+","+tfsl+","+jTextField3.getText()+","+jTextField4.getText()+","+jTextField5.getText()+","+jTextField6.getText()+");";
stm.executeUpdate(q);
JOptionPane.showMessageDialog("ADDED");
}
}
catch (Exception e){
e.printStackTrace();
}
that means you can not convert the String ":" to Number like integer or double
see below link
http://docs.oracle.com/javase/7/docs/api/java/lang/NumberFormatException.html
According to java docs
Thrown to indicate that the application has attempted to convert a
string to one of the
numeric types, but that the string does not have the appropriate format.
It means you want to convert ":" to a number which is not allowed. Hence you are getting the exception. Better show your code
The best way you get responses faster & answered your question is posting your code.
You cannot convert String to number.
As others have said Java can't convert "15:" into a number because ":" is not a digit. And the most probable cause for this is a line like this one:
int h1 = Integer.valueOf(jTextField10.getText().substring(0,2));
where you are splitting a time string at the wrong index which is why you have ":" in it.
UPDATE
Better way of splitting a time string like "12:35:09" is by using String.split():
String timeString = "12:35:09";
String[] parts = timeString.split(":");
boolean validTimeString = parts.length == 3;
The code above will result in the following values:
timeString = "12:35:09"
parts[0] = "12"
parts[1] = "35"
parts[2] = "09"
validTimeString = true
String.split(DELIMITER) will split the string into N + 1 strings where N is the number of occurences of the DELIMITER in target string.
I'm using serial event to pass rfid tags read from arduino to processing. In the serial event I am parsing and converting the variable to an integer. This working for the most part, only one rfid card keeps throwing an error.
void serialEvent(Serial thisPort)
{
String inString = thisPort.readString();
if(inString != null)
{
Serial connect1 = (Serial) connections.get(0);
if(thisPort == connect1 )
{
Chair chair = (Chair) chairs.get(0);
if(inString.contains("UID Value:"))
{
int p2 = inString.indexOf(":");
String pString = inString.substring(p2+1);
String pString2 = pString.substring (0,10);
//println(pString2);
pString2.trim();
println("String length: " + pString2.length());
chair.setRFID(pString2);
println(pString2);
}
}
}
}
void setRFID(String r)
{
try{
this.rfid = Integer.parseInt(r);
}
catch (Exception e) {
e.printStackTrace();
}
//set position of person to chair
for (Person person : people)
{
//println(this.rfid != chair.rfid);
//println(this.rfid + "," + "person: " + person.ID + "," + person.RFID);
if(this.rfid == person.RFID)
{
person.setPos(this.pos);
this.personID = person.ID;
}
}
}
The try-catch is not working, and this line is causing the problem this.rfid = Integer.parseInt(r);. I thought it might be a malformed string but the strings seems ok. Here the results of checking string consistency:
String length: 10
1811524219
String length: 10
1942302231
String length: 10
1010368230
String length: 10
9813023219
9813023219 is an invalid Integer as it is greater than Integer.MAX_VALUE, which is 2147483647. Use Long instead, who's MAX_VALUE is 9223372036854775807.
You have exceeded the maximum value for an integer. I suggest using a long instead.
Check for this by displaying Integer.MAX_VALUE - no int can exceed this value.
java.long.NumberFormatException is thrown when a given string does not match the expected layout.
The number 9813023219 is out of range for int data type, try changing your data type to long and it should work.
9813023219 is Invalid Integer, You can use Long for your requirement. If RFID is not exceeding Long.MAX_VALUE.
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))