index out of range when trying to use substring - java

I made a simple program to spell-check words. The program has 2 inputs, an array of String that works as a dictionary and a String that is a sentence. The program checks the sentence (word to word) and checks the dictionary to find a simmilar word, then it asks the user if they meant to write the word in the dictionary.
Requirements:
The first 2 characters need to be the same.
The word in the dictionary can only have 2 more characters than the sentence word.
The word in the dictionary can only have 2 different characters than the word in the sentence. (The only characters that count are the ones with index between 0 and the length of the sentence word. E.g. efg and egg|s)
public static String SpellCheck(String[] dictionary, String sentence){
Scanner sc = new Scanner(System.in);
String newSentence = "";
StringTokenizer divisor = new StringTokenizer(sentence);
while(divisor.hasMoreElements()){
String word = divisor.nextToken();
String a = "";
for(int i = 0; i<dictionary.length; ++i){
int n = 0;
if(word.length()>2 && dictionary[i].length()-word.length()<=2 && word.substring(0,2).indexOf(dictionary[i].substring(0,2))==0){
String s1 = word.substring(2,word.length());
String s2 = dictionary[i].substring(2,dictionary[i].length());
for(int k = 0; k<s1.length(); ++k){
String l1 = s1.substring(k,k+1);
String l2 = s2.substring(k,k+1);
if(l1.indexOf(l2)!=0)++n;
}
if(n<=2){
System.out.print(dictionary[i] + "?");
a = sc.nextLine();
if("yes".indexOf(a)==0){
newSentence += dictionary[i] + " ";
break;
}
}
}
}
if("yes".indexOf(a)!=0)newSentence += word + " ";
}
return newSentence;
}
The problem is at the line
String s2 = dictionary[i].substring(2,dictionary[i].length());
It works for the first word in the sentence but in the second time I get an error saying "String index is out of range" and I can't figure out why since I'm using .length() to find the index of the last letter. I hope someone can help me figuring out what's wrong with this program. Thank you!

I believe your error is in the for loop just below where you've said the error is
String s2 = dictionary[i].substring(2,dictionary[i].length());
for(int k = 0; k<s1.length(); ++k){ //HERE
String l1 = s1.substring(k,k+1);
String l2 = s2.substring(k,k+1);
}
When setting l1 and l2, you will be exceeding the bounds of your string index. the for loop should read
for(int k = 0; k < s1.length()-1; ++k){

What if the length is less than 2? Your starting index is 2.

Related

String increases in size when assigning the string an area within a char array

I've been having trouble figuring out as to why the String stringMatch is increasing in size. Since it increases in size, it goes out of bounds. I've been doing linear search through a text file and finding a word that matches what the user inputted. Does anyone see what I'm doing wrong with this code?
input = new Scanner(System.in);
System.out.print("Please enter a word to be searched or type EINPUT to quit: ");
String userString = input.next();
while(!userString.equals("EINPUT")) {
boolean bool = false;
if(userString.equals("EINPUT")) {
System.exit(1);
}
char[] charSearch = userString.toCharArray();
for(int i = 0; i < text.length; i++) {
for (int k = 0; k < (text[i].length - charSearch.length); k++) {
String stringMatch = new String(text[i], k, k + charSearch.length);
if(stringMatch.equals(userString)) {
System.out.printf("Line number %d", i + 1);
bool = true;
}
}
}
if (bool == false) {
System.out.printf("The word %s is not in the text file", userString);
}
System.out.print("Please enter a word to be searched or type EINPUT to quit: ");
userString = input.next();
}
The text document I am testing is a short one. It is as follows:
It was a beautiful sunny day
in the land of make believe
and this is the output
It w
t was
was a
was a b
as a bea
s a beaut
a beautif
a beautiful
beautiful s
beautiful sun
eautiful sunny
autiful sunny d
utiful sunny day
After it reaches the end of the first line, I get an ArrayIndexOutOfBoundsException
String stringMatch = new String(text[i], k, k + charSearch.length);
This line is the problem. The 3rd argument should be the length of the new string, not the end index. So you need to change from k + charSearch.length to charSearch.length, then it should work.

Counting upper-case characters in array with strings

So i'm trying to count the number of upper-case characters in a array with strings. I'm at a brick wall here. If someone could shed some light on my problem that would be fantastic.
I assume the same loop can be done with just Character.isLowerCase(item) as well right?
After this is completed I also have to tell the user the longest string in the array and how many characters the longest string has as well which I really don't know how to do.
Professor really threw a curve ball at us with this one..
So here's my code so far:
// Program3.java
// Brandin Yoder
// 2/23/18
// Store strings in an array and tell user number of upper-case and lower-case characters,
// and spaces
import java.util.Scanner;
public class Program3
{
public static void main(String[] args)
{
// Set up keyboard.
Scanner keyboard = new Scanner(System.in);
// Input number of strings to store.
System.out.print("Number of strings to input: ");
int nrStrings = keyboard.nextInt();
// Clear keyboard buffer.
keyboard.nextLine();
// Set up array to hold strings.
String[] strings = new String[nrStrings];
// Input strings from keyboard.
System.out.println("\nInput strings:");
for(int ctr = 0; ctr < nrStrings; ctr++)
{
System.out.print("String #" + (ctr+1) + " :");
strings[ctr] = keyboard.next();
}
// Print back strings input.
System.out.println("\nStrings input:");
for(int ctr = 0; ctr < nrStrings; ctr++)
{
System.out.println("String #" + (ctr+1) + ": " + strings[ctr]);
}
// Set up variables for upper-case, lower-case and white space calculator.
int UpperNr = 0;
int LowerNr = 0;
int Spaces = 0;
// For loop that determines amount of Upper-Case numbers.
for(int ctr = 0; ctr < nrStrings; ctr++)
{
char item = strings[ctr].charAt(ctr);
if(Character.isUpperCase(item))
UpperNr++;
}
System.out.println(UpperNr);
}
}
You need to create variables to hold the data that you want to print out at the end. In this case you need to maintain an array that has the number of Uppercases for each string as well as the index and length of the longest string. You have to use a nested for loop to iterate through the array of strings that you have and also the strings themselves in order to check how many Uppercase characters you have. I have modified/commented the last part of your code below.
//array that contains number of uppercase letters in each string
int[] upperAmount = new int[nrStrings];
//index of the longest string
int maxLenIndex = 0;
//length of longest string
int maxLength = 0;
//array that iterates through all the strings in the array strings[]
for(int i = 0; i<strings.length;i++){
//if the new string is the longest
if(strings[i].length() > maxLength){
//set maxlength to the new length and record index of string
maxLength = strings[i].length();
maxLenIndex = i;
}
// For loop that determines amount of Upper-Case numbers.
for(int ctr = 0; ctr < strings[i].length(); ctr++)
{
char item = strings[i].charAt(ctr);
if(Character.isUpperCase(item))
UpperNr++;
}
//add number of uppercases to upperAmount array indexes will be the same
upperAmount[i] = UpperNr;
//reset upper number
UpperNr = 0;
}
// Print back strings input.
System.out.println("\nStrings input:");
for(int ctr = 0; ctr < nrStrings; ctr++)
{
System.out.println("String #" + (ctr+1) + ": " + strings[ctr]);
System.out.println("Number of Uppercase Letters: " + upperAmount[ctr]);
}
System.out.println("MaxStringLength: " + maxLength);
System.out.println("Max String: " + strings[maxLenIndex]);
}
I hope this solves your problem
//after you finish printing the strings
String strMax="";
int ctr=0;
for(String str :strings ){
strMax = str.length()>strMax.length()?str:strMax;
if(!str.equals(str.toLowerCase())){
for(char c : str.toCharArray()){
if(Character.isUpperCase(c))
ctr++;
}
}
}
System.out.println("Longeset String"+strMax );
System.out.println("total Upper case chars" +ctr);
Is it neccesarry to input the count of strings? I think you can accept one whole string and convert it into array of chars
char[] charArray = acceptedString.toCharArray;
Then go throw all chars, and where charArray[n] > 64 && charArray[n] < 91 increase your variable to counting UpperCases. Hope you understand) Ask if you have questions.
Scanner keyboard = new Scanner(System.in);
String inString = keyboard.nextLine();
char[] symbol = inString.toCharArray();
int count =0;
for(int i =0; i < symbol.length; i++){
if(symbol[i] > 64 && symbol[i] < 91){ //cause every char has its own number in Unicode. 'A' = 65 and 'Z' = 90
count++;
}
}
System.out.print(count);

whats the simplest way to write a palindrome string using a while loop in java

I've searched about everywhere but I just can't find anything very concrete. I've been working on this code for awhile now but it keeps stumping me.
public static void main(String[] args) {
System.out.println(palindrome("word"));
}
public static boolean palindrome(String myPString) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word:");
String word = in.nextLine();
String reverse = "";
int startIndex = 0;
int str = word.length() -1;
while(str >= 0) {
reverse = reverse + word.charAt(i);
}
}
There's a lot of ways to accomplish this using a while loop.
Thinking about simplicity, you can imagine how could you do this if you had a set of plastic separated character in a table in front of you.
Probably you'll think about get the second character and move it to the begin, then get the third and move to begin, and so on until reach the last one, right?
0123 1023 2103 3210
WORD -> OWRD -> ROWD -> DROW
So, you'll just need two code:
init a variable i with 1 (the first moved character)
while the value of i is smaller than total string size do
replace the string with
char at i plus
substring from 0 to i plus
substring from i+1 to end
increment i
print the string
The process should be:
o + w + rd
r + ow + d
d + row +
drow
Hope it helps
Here is an piece of code I write a while back that uses almost the same process. Hope it helps!
String original;
String reverse = "";
System.out.print("Enter a string: ");
original = input.nextLine();
for(int x = original.length(); x > 0; x--)
{
reverse += original.charAt(x - 1);
}
System.out.println("The reversed string is " +reverse);

Switching letters in a string and recieving an index out of range error in Java

I'm trying to write a program that will input a sentence, and then two letters, and then switch all instances of those letters and then print out the switched sentence. For instance, they could input
I like to eat bananas
and then ā€œeā€ and ā€œa,ā€ and my program would print
I lika to aet benenes
Here is my code, but at the end it prints out String Index out of line.
Any ideas how to fix this?
System.out.println("Write something awesome.");
String input1 = Keyboard.readString();
System.out.println("Pick a letter from that awesome sentence.");
char letter1 = Keyboard.readChar();
System.out.println("Pick another letter from that awesome sentence.");
char letter2 = Keyboard.readChar();
double let1 = (input1.length());
int let1Next = (int) let1;
double let2 = (input1.length());
int let2Next = (int) let2;
String newUserImput = input1.replace(input1.charAt(let1Next),
input1.charAt(let2Next));
System.out.println(newUserImput);
Without a stack trace, I have to guess the exception is on this line.
String newUserImput = input1.replace(input1.charAt(let1Next),
input1.charAt(let2Next));
What does input1.charAt(let1Next) resolve to?
double let1 = (input1.length());
int let1Next = (int) let1;
double let2 = (input1.length());
int let2Next = (int) let2;
This can't really be what you mean.
let1Next will represent the end of the array + 1 as will let2Next.
Therefore, there are 2 major bugs here:
You are replacing all occurrences of a given character with itself.
The letter you are picking is beyond the end of the string. Remember, string indexes (such as the input to String.charAt) are 0-based, so the they range from 0 through (length - 1). By specifying input1.length, you are asking for the character after the last character of the string, hence the StringIndexOutOfBoundsException.
You can iterate over array that contains all characters of user sentence (you can get such array using toCharArray method invoked on input1) and if you find letter1 replace it with letter2 and vice-versa.
After that you can create new string based on updated array with new String(arrayOfCharacters).
The method replace will replace all chars in the string
So what you want is
String new1 = input1.replace (letter1, letter2);
String new2 = input1.replace (letter2, letter1);
Then iterate over the original string to see what is different in new1 and new2.
Try using char array-
char letter1 = 'a';
char letter2 = 'e';
String s = "I like to eat bananas";
char[] chrs = s.toCharArray();
int n = chrs.length;
for (int i = 0; i < n; i++) {
if (chrs[i] == letter1) {//if array contains letter1 at intdex i
chrs[i] = letter2; //replace with letter 2
} else if (chrs[i] == letter2) { //if array contains letter2 at intdex i
chrs[i] = letter1;//replace with letter 1
}
}
String swapedString = new String(chrs);
System.out.println(swapedString );
try with this.
char[] cs = input1.toCharArray();
for (int i = 0; i < cs.length; i++) {
char c = cs[i];
if (letter1 == c) {
cs[i] = letter2;
} else if (letter2 == c) {
cs[i] = letter1;
}
}
String newUserImput = new String(cs);
You are getting String index out of line because you tried to access characters outside of the string (valid range is from 0 to length-1). And even if you used length-1, your code will not do what you want. What you really need is to have two dummy placeholders (I assume your string will never contain '#' or '$') replacing 'a' and 'e' and then swap 'a' and 'e' with the dummy placeholders. The code follows:
System.out.println("Write something awesome.");
String input1 = "I like to eat bananas";//Keyboard.readString();
System.out.println("Pick a letter from that awesome sentence.");
char letter1 = 'e';
System.out.println("Pick another letter from that awesome sentence.");
char letter2 = 'a';
// dummy placeholders
char letter3 = '#';
char letter4 = '$';
String newUserImput = input1.replace (letter1, letter3);
newUserImput = newUserImput.replace (letter2, letter4);
newUserImput = newUserImput.replace (letter3, letter2);
newUserImput = newUserImput.replace (letter4, letter1);
System.out.println(newUserImput);

JAVA basic iterator

this was the solution to my homework and the purpose was to reverse each word in a string based on user inputting a sentence. I have completed this on my own, but I'm just wondering how the iterator worked in this piece of code. I don't understand the delcaration of tempword = ""; and how he printed out each word delimited by spaces.
import java.util.Scanner;
public class StringReverser
{
public static void main(String args[])
{
String sentence;
String word;
String tempWord = "";
Scanner scan = new Scanner(System.in);
Scanner wordScan;
System.out.print("Enter a sentence: ");
sentence = scan.nextLine();
wordScan = new Scanner(sentence);
while(wordScan.hasNext())
{
word = wordScan.next();
for(int numLetters = word.length() - 1; numLetters >= 0; numLetters--)
tempWord += word.charAt(numLetters);
System.out.print(tempWord + " ");
tempWord = "";
}
System.out.println();
}
}
this bit adds in the spaces
System.out.print(tempWord + " ");
this bit reverses it
for(int numLetters = word.length() - 1; numLetters >= 0; numLetters--)
tempWord += word.charAt(numLetters);
this bit sets it up for the next word
tempWord = "";
The for loop counts backwards, from the index of the last character in the word to the first (in zero based notation)
The print prints the reversed word + a space (" "), the fact it uses print in place of println is because println would add a carriage return putting each word in a different line.
The tempWord = ""; at the end of each iteration reset the variable so it can be reused.

Categories

Resources