Java- index out of range: 0 - java

I am desperately trying to figure out a way of stopping "String index out of range: 0" errors... It happens whenever I don't enter anything and then continue execution:
static String getRef(Scanner Keyboard)
{
Scanner keyboard = new Scanner(System.in);
String ref= "";
boolean valid = false;
int errors = 0;
boolean problem = false;
while(valid==false)
{
System.out.println("Please enter a reference number which is two letters followed by three digits and a letter(B for business accounts and N for non business accounts)");
ref = keyboard.nextLine();
for (int i=0; i<6; i++)
{
if (ref.charAt(i)=='\0')
{
problem = true;
}
}
if(problem == true)
{
System.out.println("The reference must consist of 6 Characters");
}
else
{
if ((Character.isDigit(ref.charAt(0))== true) || (Character.isDigit(ref.charAt(1))== true))
{
System.out.println("The first 2 characters must be letters");
errors = errors + 1;
}
if ((Character.isDigit(ref.charAt(2))== false) || (Character.isDigit(ref.charAt(3))== false)||(Character.isDigit(ref.charAt(4))== false))
{
System.out.println("The 3rd,4th and 5th characters must be numbers");
errors = errors + 1;
}
if ((!ref.toUpperCase().endsWith("B"))&&(!ref.toUpperCase().endsWith("N")))
{
System.out.println("The 6th character must be either B(for business accounts) or N(for non business accounts) ");
errors = errors + 1;
}
if (errors==0)
{
valid=true;
}
}
}
return ref;
}
What I want is to be able to output an error message if the string does not contain a character at a certain index e.g. ref.charAt(0).
This will help (example):
if(ref.charAt(aNumber)==null) {
// display error message
}

Your problem is here:
ref.charAt(i)=='\0'
What happens if ref is a zero length string? In that case, trying to access the character at index 0 (where the first character would normally be) will give you your index out of range: 0 error. Make sure you test the string length first:
if (ref != null && !ref.isEmpty() &&ref.charAt(i)=='\0') { .. }

Adding a length() check
ref is empty (that is "") when you don't enter anything. So you can't get the character at 0 (or 1, 2, 3 ...). You can add an if check on the length, something like
if (ref.length() > 5) {
for (int i = 0; i < 6; i++) {
if (ref.charAt(i) == '\0') {
problem = true;
}
}
} else {
System.out.println("Please enter at least 6 characters");
}
Regular Expression
It might be simpler to compile a (reusable) Pattern with a regular expression to validate your reference criteria (2 letters, followed by 3 digits, followed b or n). Something like,
String ref; // <-- get input
Pattern p = Pattern.compile("([a-zA-Z]{2})(\\d{3})([B|N|b|n])");
Matcher m = p.matcher(ref);
if (m.matches()) { // <-- valid = m.matches();
System.out.println("ref is valid");
} else {
System.out.println("ref is not valid");
}

Related

How to validate string if the first 3 positions are letters

I'm trying to validate a string entered by a user. The user must enter a string with 7 characters; the string first 3 characters must be letters and the last 4 must be numbers.
I wrote this piece of code( as a method ) but for some reason it accepts the first character as a number ( which it's suppose to be a letter ) and the rest are numbers. For example :
Please enter word : **1gy2345**
This will enter the loop, as wanted, and move on into the next method in the main.
If the user enters a word that its length is bigger than 7 it will ask him to enter a valid word.
For example :
Please enter word : **bob12345**
The word entered is invalid. Please enter a word beginning with 3 letters and ending with 4 numbers ( The word must be 7 characters long ).
Here is my code:
public static final String solicitationMessage = " Please enter word ";
public static final String errorMessage = " The word entered is invalid. Please enter a word beginning with 3 letters and ending with 4 numbers ( The word must be 7 characters long ).
public static final int lengthOfString = 7;
public static String validateString(String solicitationMessage, String errorMessage, int lengthOfString) {
System.out.print(solicitationMessage);
String word = keyboard.nextLine();
while (!( word.length() == lengthOfString )) {
if (((word.charAt(0) <= 'a' || word.charAt(0) >= 'z') || (word.charAt(1) <= 'a' || word.charAt(1) >= 'z')
|| (word.charAt(2) <= 'a' || word.charAt(2) >= 'z'))) {
System.out.print(errorMessage);
System.out.print(solicitationMessage);
word = keyboard.nextLine();
}
}
return word;
}
However, if I enter a string higher than the 7 limit character it will ask me again the enter a valid string like it's suppose to do.
The use of regex is not permitted.
Any help ?
This is easy task for regex
[a-zA-Z]{3}[0-9]{4}
Some test cases: http://www.regexplanet.com/cookbook/ahJzfnJlZ2V4cGxhbmV0LWhyZHNyEwsSBlJlY2lwZRiAgICi0ZuYCgw/index.html
So it can be something like
Pattern pattern=Pattern.compile("[a-zA-Z]{3}[0-9]{4}");
String line;
while(true){
line= keyboard.nextLine();
if(pattern.matcher(line).matches()){
break;
}
}
Since this is an assignment I will only give you the pseudo code. You try to figure out how to implement it :p
boolean function validateString(inputString):
check if inputStrings length is exactly 7:
if not then return false;
loop through inputString:
if the current index is less than 3 and current character is within 'a' - 'z' or within 'A' - 'Z' // check if current character is a letter
return false;
else if current index is greater than 2 and current character is not within '0' - '9' // check if current character is not a digit
return false;
end loop
return true
end function
Then just call that function in your main method and print necessary error messages.
Try this. Use the Character class to test the characters.
if (!(Character.isLetter(word.charAt(0)) &&
Character.isLetter(word.charAt(1)) &&
Character.isLetter(word.charAt(2)))) {
System.out.print(errorMessage);
System.out.print(solicitationMessage);
word = keyboard.nextLine();
}
May be this would help.
public static String validateString(String solicitationMessage, String errorMessage, int lengthOfString) {
System.out.print(solicitationMessage);
String word = "";
boolean flag = false;
while (true) {
Scanner sc = new Scanner(System.in);
word = sc.nextLine();
if(word.length() == lengthOfString){
for(int i=0;i<word.length();i++){
int ascii = (int)word.charAt(i);
if(i<3 && (ascii > 64 && ascii < 123)){
flag = true;
}else if(i>2 && (ascii > 47 && ascii < 58)){
flag = true;
}else{
flag = false;
System.out.println(errorMessage);
break;
}
}
if(flag){
break;
}
}else{
System.out.println(errorMessage);
}
}
return word;
}

Evaluate the Last 2 Digits of an Int?

I need to make a program that reads hours in this format (934:9h34) or 1835 (18h35). How can I make my program print an error if somebody writes 966 (the 2 last digits over 59? (66>59)
Given a String str:
String str = getTheString();
String lastTwoDigits = str.length() > 2 ? str.substring(str.length() - 2) : str;
int result = 0;
try {
result = Integer.parseInt(lastTwoDigits);
} catch (NumberFormatException e) {
System.err.println("Cannot parse string!");
System.exit(1);
}
if (result > 59) {
System.err.println("Number was over 59!");
System.exit(1);
}
By the way, System.err.println() just prints to standard error rather than standard output, and exit(1) exits the program with a failing error code.
Hope this helps!
This solution will parse the string first, then get the last two digits of the number through result % 100.
private static void timeFormat(String text) {
int result = 0;
if (text.length() < 2) {
System.err.println("String was too short");
return;
}
try {
result = Integer.parseInt(text);
} catch (NumberFormatException e) {
System.err.println("Failed to parse string");
}
if (result % 100 > 59) {
System.err.println("Number was over 59");
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
timeFormat(scan.nextLine());
scan.close();
}
Since the title asks "How to evaluate the 2 last digit of a Int?", we can assume that you already have the value in an int variable.
To examine the last 2 digits, calculate the remainder when dividing by 100, i.e. use the % remainder operator:
int value = /*assigned elsewhere*/;
int lastTwoDigits = value % 100;
if (lastTwoDigits > 59) {
System.out.println("ERROR: Invalid value: " + value);
// value is invalid
}
Of course, you should probably also validate that value is not negative.
If, however, a value of -934 is valid, and -966 is not, just eliminate the sign by calling Math.abs():
int lastTwoDigits = Math.abs(value) % 100;
if (lastTwoDigits > 59) {
System.out.println("ERROR: Invalid value: " + value);
// value is invalid
}
This will work. Ensures that last 2 digits are <= 59.
String[] test = { "934:9h34", "1835", "1994", "iwiwiwiw45", "18h45"
};
// match 2 digits at end of string
Pattern p = Pattern.compile("(\\d\\d)$");
for (String t : test) {
Matcher m = p.matcher(t);
if (m.find()) {
// valid integer so convert and compare
if (Integer.valueOf(m.group(1)) <= 59) {
System.out.println("Passes test: " + t);
continue;
}
}
System.out.println("Fails test: " + t);
}
Learn more about Java and regular expressions
here.
First convert user given input into String
String hourInString = Integer.toString(userInput);
Then check if the input is valid or not. Minimum length of the input should be at least 3.
if (hourInString.length() < 3) {
System.out.println("invalid input");
System.exit(1);
}
Then retrieve the last two digit using substring
String lastTwoDigit = hourInString.substring(hourInString.length() - 2,
hourInString.length());
Finally you can validate the number-
if (Integer.parseInt(lastTwoDigit) > 59) {
System.out.println("Error");
}

Java check String input

I am trying to check an input String:
- length
- type
- special char at the end
The input is a identity card like this 24659213Q.
So what I got for now is:
public void datosUsuario() {
System.out.print("Write ID: ");
input = scanner.nextLine();
}
//ID check
public void comprobacion() {
System.out.println("Checking ID length...");
if (input.length() == 9){
status = true;
System.out.println("Length: OK!");
} else {
System.out.println("Length not OK! Try again!\n");
status = false;
}
}
So I am checking the entire String for having 8+1 length and now I am having problems checking if it has 8 digits and a char at the end of the input.
Any ideas would be apreciated! Thank you!
I'd use a regular expression:
String input = scanner.nextLine();
input.matches("/^[0-9]{8}[A-Za-z]$/);
See String.matches and regular expression documentation.
A simple method would be:
//ID check
public void comprobacion() {
System.out.println("Checking ID length...");
if (input.length() == 9) {
if (Character.isAlphabetic(input.charAt(8)) {
status = true;
System.out.println("OK!");
} else {
status = false;
System.out.println("Length: OK, but last character must be alphabetic");
}
} else {
System.out.println("Length not OK! Try again!\n");
status = false;
}
You can use reg ex,
public static void comprobacion(String input) {
status = false;
if(input.matches("\\d{8}\\w{1}"))
{
status = true;
}
}
Here, \d{8} = eight digits
\w{1} = one alphabetical character
You could use "Character.isDigit()" to determine if a character is a digit or not. In other words, you could create a for loop to interate through each character, checking whether it is a digit or not. Here's an example:
String input = "24659213Q";
for(int c = 0; c < input.length()-1; c++){
//Checks all but the last character
if( !Character.isDigit( input.charAt(c) ) ){
System.out.println("The String does not start with 8 digits");
}
}
if( Character.isDigit( input.charAt(8) ) ){
//Checks only last character
System.out.println("The String does not end with a char");
}
The method of regular expression can also be followed as mentioned above. There is one more way to do it.
1)Split the string into two -one with 8 characters and the other with last one character.
2)Parse the first String
Integer.parseInt(subStringOfFirst8Char) in a try catch block catching NUmberFormatException.
If you don't catch the exception it is alright else it is wrong.

Tweet testing program

Hello I have a working code for testing the amounts of hashtags, attributions, and links in the program but I need to test for if there is a tab key or space used after either the hashtags or attributions so as to not count them and have been having trouble.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a tweet: ");
String input = scan.nextLine();
int length = input.length();
int count = 0;
int hashtags = 0, attributions = 0, links = 0;
char letter;
char letter2;
if (length > 140) {
System.out.println("Excess Characters: " + (length - 140));
} else {
while (count < length) {
letter = input.charAt(count);
if (letter == '#') {
if (input.startsWith("#\t", count)) {
} else {
hashtags++;
count++;
}
if (letter == '#') {
if (input.startsWith("#\t", count)) {
count++;
} else {
attributions++;
count++;
}
}
if (letter == 'h') {
input = input.toLowerCase();
if (input.startsWith("http://", count)) {
links++;
count++;
} else {
count++;
}
} else {
count++;
}
}
System.out.println("Length Correct");
System.out.println("Number of Hashtags: " + hashtags);
System.out.println("Number of Attributions: " + attributions);
System.out.println("Number of Links: " + links);
}
}
}
}
One easy way:
Call Character.isWhitespace(char). (Example: Character.isWhitespace(input.charAt(count+1))). Obviously you'd need to check to make sure that the hashtag isn't the last character.
Some unsolicited advice:
Try not to use .startsWith(), because that is limited to specific characters, and you'd have to add a different if statement for each character you wanted to check for (space, tab, etc.). I recognize that this might not work in all cases, such as your .startsWith("http:") case. In this case, .startsWith() can still work, but use the count to get the index: input.substring(count).startsWith("http:") (Documentation here)
One issue your code currently faces is that the checking of spaces always goes from the beginning of a string. For the input string #\tabc #def #ghi, it will show 0 hashtags, because it fails the space on the first case, which is the one it's checking every time.
If you are constantly doing if (letter=='<char>'), you might want to try using a switch statement (e.g. switch(letter)). In Java, this works on characters (or Strings, if you are using Java 8). This can help avoid difficult-to-trace errors regarding bracket placement, etc.

help with making a password checker in java

I am trying to make a program in Java that checks for three specific inputs. It has to have pass these tests:
At least 7 characters.
Contain both upper and lower case alphabetic characters.
Contain at least 1 digit.
So far I have been able to make it check if there is 7 characters, but I am having trouble with the last two. What should I put in my loop as an if statement to check for digits and make it upper and lower case. Any help would be greatly appreciated.
Here is what I have so far.
import java.awt.*;
import java.io.*;
import java.util.StringTokenizer;
public class passCheck
{
private static String getStrSys ()
{
String myInput = null; //Store the String that is read in from the command line
BufferedReader mySystem; //Buffer to store the input
mySystem = new BufferedReader (new InputStreamReader (System.in)); //creates a connection to system input
try
{
myInput = mySystem.readLine (); //reads in data from the console
myInput = myInput.trim ();
}
catch (IOException e) //check
{
System.out.println ("IOException: " + e);
return "";
}
return myInput; //return the integer to the main program
}
//****************************************
//main instructions go here
//****************************************
static public void main (String[] args)
{
String pass; //the words the user inputs
String temp = ""; //holds temp info
int stringLength; //length of string
boolean goodPass = false;
System.out.print ("Please enter a password: "); //ask for words
pass = getStrSys (); //get words from system
temp = pass.toLowerCase ();
stringLength = pass.length (); //find length of eveyrthing
while (goodPass == false)
{
if (stringLength < 7)
{
System.out.println ("Your password must consist of at least 7 characters");
System.out.print ("Please enter a password: "); //ask for words
pass = getStrSys ();
stringLength = pass.length ();
goodPass = false;
}
else if (/* something to check for digits */)
{
}
}
Sure you can come up with a convoluted—almost unreadable—regex for doing this but I wouldn't suggest it. Apart from the readability aspect, if the password fails it doesn't tell you why. This solves both of these problems:
while (true) {
pass = getStrSys();
if (pass.length() < 7) {
System.out.println("must be at least 7 characters long");
} else {
boolean upper = false;
boolean lower = false;
boolean number = false;
for (char c : pass.toCharArray()) {
if (Character.isUpperCase(c)) {
upper = true;
} else if (Character.isLowerCase(c)) {
lower = true;
} else if (Character.isDigit(c)) {
number = true;
}
}
if (!upper) {
System.out.println("must contain at least one uppercase character");
} else if (!lower) {
System.out.println("must contain at least one lowercase character");
} else if (!number) {
System.out.println("must contain at least one number");
} else {
break;
}
}
}
A regular expression is more appropriate for what you are trying to accomplish. For instance, using lookahead assertions, you'd use something like this:
Pattern p = Pattern.compile("^.*(?=.{7,})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$");
String pass = getStrSys();
Matcher m = p.matcher(pass);
if (m.matches()) {
System.out.println("Valid password.");
} else {
System.out.println("Invalid password.");
}
Don't use StringTokenizer. Use String.split.
Use the functions in the Character class to check for upper case, lower case, or numeric.
Since you've forced lower case, you can't check. You need to get rid of that.
In your situation. There should be two condition true for validation. I think following will be the best approach to achieve it.
private static final char[] SPECIAL = "$!+\-#?_%&/".toCharArray();
private static final char[] NUMBER = "0123456789".toCharArray();
public static boolean checkValidation(String password)
{
int points = 0;
String lowerPass = password.toLowerCase();
String upperPass = password.toUpperCase();
if(!password.equals(lowerPass) && !password.equals(upperPass))
{
// if contains upper or lower letter
points++;
}
if(contains(password, SPECIAL))
{
// if it contains special character
points++;
}
if(contains(password, NUMBER))
{
// if it contains Number
points++;
}
return points >= 2;
}
public static boolean contains(String pwd, char[] value)
{
int i = 0;
boolean success = false;
while(i < value.length && !success)
{
if(pwd.indexOf(""+value[i]) != -1)
{
success = true;
}
i++;
}
return success;
}

Categories