Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11 - java

I'm writing a simple spell checker program , but i'm having trouble with a loop and i can't seem to figure it out. Here's my code
public class spellchecker {
public static void main(String[] args) {
// setting up dictionary
String[] dictionary = {"win","winner","know","born","were","plan","must","you","correct","college", "to"} ;
//defining our sentence
String sentence = "You were born to win but to be a winners you must plan to win prepare to win and expect to win";
//splitting sentence into an array of words
String[] split = sentence.split("\\s");
for(int i = 0; i<split.length; i++)
{
if(split[i].equals(dictionary[0]) || split[i].equals(dictionary[1]) || split[i].equals(dictionary[2]) || split[i].equals(dictionary[3]) || split[i].equals(dictionary[4]) || split[i].equals(dictionary[5]) || split[i].equals(dictionary[6]) || split[i].equals(dictionary[7]) || split[i].equals(dictionary[8]) || split[i].equals(dictionary[9]) || split[i].equals(dictionary[10]) || split[i].equals(dictionary[11]))
{
System.out.println(split[i] + " is valid");
}
else
{
System.out.println(split[i] + " is invalid, please correct");
}
}
}
}

Indices for an array only run from 0 through n - 1. Here, with a dictionary array of length 11, that's 0 through 10. However, you explicitly reference index 11 here:
|| split[i].equals(dictionary[10]) || split[i].equals(dictionary[11]))
You're checking all of them explicitly, starting with 0, so just remove that last one (11).
|| split[i].equals(dictionary[10]))
But what if you add 5 more words to the dictionary? 50? Your long chain of if conditions will also need to grow. For flexibility, you should consider a for loop over all of the contents of the dictionary array. Even better, consider using a HashSet to store your dictionary words, so that you don't have to scan the entire dictionary for every entered word.

Your array has 11 elements (0 - 10). So 11 is out of bounds.
split[i].equals(dictionary[11]
You might really want to consider using a loop in some way rather than hardcoding your indexes.

for a more general solution, replace your big if with:
if(Arrays.asList(dictionary).contains(split[i]))
This will work for any dictionary.

Remove split[i].equals(dictionary[11]) from your if() condition
i.e.
Your if could be
if(split[i].equals(dictionary[0]) || split[i].equals(dictionary[1]) || split[i].equals(dictionary[2]) || split[i].equals(dictionary[3]) || split[i].equals(dictionary[4]) || split[i].equals(dictionary[5]) || split[i].equals(dictionary[6]) || split[i].equals(dictionary[7]) || split[i].equals(dictionary[8]) || split[i].equals(dictionary[9]) || split[i].equals(dictionary[10]))

Related

how find the number of conditions in a control structure for a given code segment in java

I want to get the count of conditions a control structure for a given code segment line by line.Can someone help me to get a correct output?
public int[] countCon() {
char opArray[] ={'<','>','=','!'};
String[] lines = code.split("\\r?\\n");
int[] score = new int[lines.length];
int s = 0;
score[s] = 0;
for(String line : lines) {
String tline = line;
if(tline.contains("if") || tline.contains("else if") || tline.contains("while") || tline.contains("do") || tline.contains("for") || tline.contains("switch") || tline.contains("case ")){
if (line.indexOf("if") != -1 ) {
for(int i = 0;i<=opArray.length-1;i++) {
//tline.contains.new String(opArray[i]);
opArray[i]++;
if(tline.contains("<") || tline.contains(">") || tline.contains("<=") || tline.contains(">=") || tline.contains("==") || tline.contains("!")) {
score[s] = score[s]+1;
}
else {
score[s]=0;
}
}
}
}
}
}
This is not a trivial task since the input provided can be in very different styles. The simplest way is to use regular expressions that match on branching keywords such as if (including else if), while, for, etc.. If you are disregarding method calls.
In case you don't want to use regex, your code can be improved too: no need to consider nesting conditions or boolean expressions inside the branching construct. This is because no operators except (tenery exp ? a : b) introduces branching.

Is there a way to shorten something like this?

In this part of the code, a scanner asks the user to input a number between one and five. I will need to rewrite this for a bunch of variables, so is there any way to make it shorter?
if (Q1 != 1 || Q1 != 2 || Q1 != 3 || Q1 !=4 || Q1 != 5) {
System.out.println("Error: Please enter a number between 1 and 5.");
}
Instead of typing Q1 != 1 or 2 or 3 etc, is there a way to write 1-5 or something like that?
Try this,
if(Q1 <1 || Q1 >5) System.out.println("Error: Please enter a number between 1 and 5.")
For the general case, use a set.
Declare a class field, or a local variable:
Set<Integer> accepted = new LinkedHashSet<>(Arrays.asList(1,2,3,4,5));
Then:
if (!accepted.contains(Q1))
System.out.println("Error: Please enter a number that is one of: " + accepted);
Use LinkedHashSet so the printed version has the same order as the declaration.
The above answers are nice for this specific problem, but if you have 5 separate Strings for example, and you want to check if each of them are valid (they aren't null or empty), then you should create a method, to do that.
public boolean isValid(String... args) {
for (String s : args) {
if (s == null or s.equals("")) {
//Something is invalid
return false;
}
}
//Everything is valid
return true;
}

How to compare two strings, of different length to find identical substring

The problem is:
Client accounts are filed under a classification system using codes eg MA400. I need a method that will reset the original MA400 to an updated code such as MA400.4. If the new code has 5 characters to which the original is reset then the method returns true. Not the best wording but that is all I have right now.
It hasn't been specified if the characters need to be in the same order, eg.
String str = "abc123";
String newStr = "xyz123abc";
I am assuming they need to be in the same order. So the above strings would only have 3 like characters.
char[]array = str.toCharArray();
char[]array2 = newStr.toCharArray();
I am thinking now to use a compareTo method on the two arrays, but I am not sure how this would work exactly. Perhaps I could use a for loop to stop comparing after the final element in the shortest string but not entirely sure if I can do much with that.
I feel like I am going about this in the wrong way and there is a less complicated way to check for like characters in a string?
From what I understand something like this will work. Remember this will only count unique characters. Order does not matter
public static boolean matchingChar(final String st1, final String st2) {
if(st1 == null || st2 == null || st1.length() < 5 || st2.length() < 5) {
return false;
}
//This is if you wish unique characters to be counted only
//Otherwise you can use simple int count = 0
HashSet<Character> found = new HashSet<Character>();
//found.size() < 5 so the loop break as soon as the condition is met
for(int i = 0; i < st1.length() && found.size() < 5; i++) {
if(st2.indexOf(st1.charAt(i)) != -1) {
found.add(st1.charAt(i));
}
}
return found.size() >= 5;
}

I'm confused about Logical Operators, can someone help me clear up my mess? Multiple arguments?

this is my first post here, but I often use this site to help me with coding issues I run into. I'm an intermediate level Java programmer. I'm going to college next year and I'm considering a minor in Computer Science.
I'm making a pretty basic mock-credit card validator that reads in a credit card, checks if it's valid, and then emails information to the user. This is not to be used for anything other than educational purposes.
So I have a bit of code that checks multiple conditions for a credit card string that someone types in. For example, as you'll see, it checks the starting digit, the name of the card, and the number of digits. It checks the conditions, and if they are met the program continues, if not it gives an error and stops immediately. I'm like 99% sure that I'm entering my information in correctly, but it gives me the error no matter what and I'm at a loss here.
Sorry if I typed so much, again I'm new here. So I'm asking for help on my logic here, thanks!
if((cardType.equals("Visa") && card.substring(0).equals("4")) && (length == 13 || length == 16)){
System.out.println("Thank you, next step");
cardValid = true;
}
if((cardType.equals("Master Card")) && (card.substring(0,1).equals("51") || card.substring(0,1).equals("52") || card.substring(0,1).equals("53") || card.substring(0,1).equals("54") || card.substring(0,1).equals("55")) && (length == 16)){
System.out.println("Thank you, next step");
cardValid = true;
}
if((cardType.equals("American Express") && card.substring(0,1).equals("37") && length == 15)){
System.out.println("Thank you, next step");
cardValid = true;
}
if(cardValid != true){
System.out.println("ERROR");
System.exit(0);
}
}
You are not using the substring method correctly. To get the first character as a substring, you need to use the two-argument version of substring, to supply a beginning index (inclusive) and an ending index (exclusive).
The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
Parameters:
beginIndex - the beginning index, inclusive.
endIndex - the ending index, exclusive.
(The one-argument version of substring takes a substring from the given index through the rest of the string.)
The substring begins with the character at the specified index and extends to the end of this string.
Replace
card.substring(0).equals("4")
with
card.substring(0, 1).equals("4")
or just compare the character there.
card.charAt(0) == '4'
Next, to get the first two characters, again take into account the fact that the ending index is exclusive. Replace
card.substring(0,1).equals("37")
with
card.substring(0,2).equals("37")
The following should work.
You had some syntactic errors with String.substring. You can refer to a full list of String functions in the java documentation below:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
if((cardType.equals("Visa") && card.substring(0,1).equals("4")) && (length == 13 || length == 16)){
System.out.println("Thank you, next step");
cardValid = true;
}
if((cardType.equals("Master Card")) && (card.substring(0,2).equals("51") || card.substring(0,2).equals("52") || card.substring(0,2).equals("53") || card.substring(0,2).equals("54") || card.substring(0,2).equals("55")) && (length == 16)){
System.out.println("Thank you, next step");
cardValid = true;
}
if((cardType.equals("American Express") && card.substring(0,2).equals("37") && length == 15)){
System.out.println("Thank you, next step");
cardValid = true;
}
if(!cardValid){
System.out.println("ERROR");
System.exit(0);
}
}

How to make sure the user only inputs 1s and 0s?

I have this loop that keeps the user stuck inputting values until he/she, inputs something valid, in this case it has to be binary numbers that must be the size of a certain type of variable. Nonetheless, I don't know how to make the loop continue in the case that the user inputs a number made up of something different aside from 1s and 0s.
I was thinking of using string.contains(), but that cannot account for every number. Here's my loop:
while((double)inputStr.length() != table.getNumberOfVariables() ||
inputStr.replaceAll("\\D","").length() != inputStr.length() ||
Double.parseDouble(inputStr) > 1){
This line: Double.parseDouble(inputStr) > 1 was supposed to accomplish that, but I'm dealing with decimal numbers, so if the input is 10 or 100, they're rendered invalid.
In your case, rather than using \D in your regex (anything that's not a digit), you must be more specific: [^01] (meaning: anything not a zero or one).
while((double)inputStr.length() != table.getNumberOfVariables() ||
inputStr.replaceAll("[^01]","").length() != inputStr.length() ||
Double.parseDouble(inputStr) > 1){
It doesn't win you a prize for nice code though, because it is hard for the reader of this code to find out what you are doing. It's better to turn what you're doing into a method with a clear name, like:
public static boolean containsOnly(String s, String only) {
for (int i = 0; i < s.length(); i++) {
if (only.indexOf(s.charAt(i)) == -1)
return false;
}
return true;
}
As it happens, the Apache commons-lang3 library has such a method in it: StringUtils.containsOnly. They have many methods for String manipulation that are clearer and often much faster than using regexes.
You can use a regular expression to validate the binary string:
String s = "0101110";
if (s.matches("[01]++")) {
System.out.println("ok");
} else {
System.out.println("invalid");
}

Categories

Resources