valid word counter out of bounds error [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
{
public static int WordCount (String cString)
{
String currentWord;
int index;
int spacePos;
int validWordCount=0;
boolean validWord;
char upClowC;
cString=cString.trim()+" ";
spacePos=cString.indexOf(" ");
validWord=true;
for(index=0;index<cString.length();index++)
{
currentWord=cString.substring(0,spacePos);
upClowC=Character.toUpperCase(currentWord.charAt(index));
if(upClowC<'A'||upClowC>'Z')
{
validWord=false;
}
}
if(validWord==true)
{
validWordCount++;
}
return validWordCount;
}
public static void main(String[] args)
{
String sentence;
System.out.println("enter a sentence:");
sentence=EasyIn.getString();
WordCount(sentence);
}
}
I'm trying to create a method which takes a sentence and picks out the valid words (i.e. no numbers or symbols), but I keep getting an out of bounds error.
I can't use an array.

Your problem is here:
currentWord = cString.substring(0, spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
currentWord gets shorter, but index is still running from 0 to the length of the string.
General notes:
Follow Java naming conventions and change the name of your method to begin with small letter
if(validWord) is enough when you want to compare something to true, otherwise it's like asking "is it true that the value is true" instead of simply "is the value true"
Next time post your stack trace to get better and sooner help

In your code, you are doing
spacePos = cString.indexOf(" ");
And then inside the loop:
currentWord = cString.substring(0,spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
Now, because of the loop, the index will take values from 0 to your string length minus 1. If your substring (currentWord) is smaller than your string - which probably is -, then currentWord.charAt(index) will try to index out of the bounds of the substring, which is why you get the error.

Related

Java - Event handle data protection for Strings with 2 data types [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
For event handling how can you check a string that has a combination of integers and a character?
For example - 1234p
If the user enters the example above, how can you check if the user enters integers first and then a character at the end? What kind of exception will be thrown if the data type input is not an integer or char?
You can use REGEX [0-9]+[a-zA-Z] to match if the string contains chars and integers otherwise throw an IllegalArgumentException
public void check(String input) {
if (!input.matches("[0-9]+[a-zA-Z]")) {
throw IllegalArgumentException("Not valid string");
}
// do other logic
}
So from your question it sounds like you expect a string that has all numbers except the last character that has to be an alphabet. You can check if the given string matches this condition the following way too:
String string = "1234p";
int length = string.length();
boolean numsFirst = string.substring(0, length - 1).chars().allMatch(x -> Character.isDigit(x));
boolean lastChar = Character.isDigit(string.charAt(length - 1));
if(numsFirst && lastChar)
return true;
else
return false;

String index out of range even though the string is limited [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am a student and I am learning Java.I recently got a question which said I had to find the largest word in a given string..I wrote a code but it is giving me an error that string index is out of bounds even though I limited it to the length of the string..Can someone help me with the code..Please use simple language(I am not an expert)
Code
import java.util.*;
class word
{
void def()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
String s1=sc.nextLine();
int length=s1.length();
length++; //My name
int j=0; //0123456
int word=0;
int findex=0;
int lindex=0;
int lword=0;
for(int i=0;i<length;i++)
{
if(s1.charAt(i)==' ' && j==0)
{
lword=i;
findex=0;
lindex=i;
j=i;
}
else if(s1.charAt(i)==' ')
{
if(i-j-1>lword)
{
findex=j;
lindex=i;
lword=i-j-1;
}
j=i;
}
else if(i==length-1)
{
if(i-j-1>lword)
{
findex=j;
lindex=i;
}
}
}
System.out.println("Largest word is:"+s1.substring(findex,lindex+1));
}
}
By doing length++ you make sure that your length variable will be larger then the actual string length. at the last loop step there will be no char at s1.charAt(i)
Just remove the line with length++

How to split a string at every Nth occurrence of a character in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to split a String at every Nth occurence, but missing the last values.Here is what is expected.
Input : String str = "234-236-456-567-678-675-453-564";
Output :
234-236-456
567-678-675
453-564
Here N=3, where the str should be split at every 3rd occurence of -.
Try this.
String str = "234-236-456-567-678-675-453-564";
String[] f = str.split("(?<=\\G.*-.*-.*)-");
System.out.println(Arrays.toString(f));
result:
[234-236-456, 567-678-675, 453-564]
You can try the following with Java 8:
String str = "234-236-456-567-678-675-453-564";
Lists.partition(Lists.newArrayList(str.split("-")), 3)
.stream().map(strings -> strings.stream().collect(Collectors.joining("-")))
.forEach(System.out::println);
Output:
234-236-456
567-678-675
453-564
Maybe one of the worst way without using function available in java , but good like exercise :
public static void main(String[] args){
String s = "234-236-456-567-678-675-453-564";
int nth =0;
int cont =0;
int i=0;
for(;i<s.length();i++){
if(s.charAt(i)=='-')
nth++;
if(nth == 3 || i==s.length()-1){
if(i==s.length()-1) //with this if you preveent to cut the last number
System.out.println(s.substring(cont,i+1));
else
System.out.println(s.substring(cont,i));
nth=0;
cont =i+1;
}
}
}

Check a string for consecutive repeated characters [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
It is asked in an interview to write the code in Java to display the string which doesn't have consecutive repeated characters.
E.g.: Google, Apple, Amazon;
It should display "Amazon"
I wrote code to find continues repeating char. Is there any algorithm or efficient way to find it?
class replace
{
public static void main(String args[])
{
String arr[]=new String[3];
arr[0]="Google";
arr[1]="Apple";
arr[2]="Amazon";
for(int i=0;i<arr.length;i++)
{
int j;
for(j=1;j<arr[i].length();j++)
{
if(arr[i].charAt(j) == arr[i].charAt(j-1))
{
break;
}
}
if(j==arr[i].length())
System.out.println(arr[i]);
}
}
}
Logic : Match the characters in a String with the previous character.
If you find string[i]==string[i-1]. Break the loop. Choose the next string.
If you have reached till the end of the string with no match having continuous repeated character, then print the string.

Store all possible substring in String [] [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to store all possible substring in String []. I tried this but got an error:
public void sub(String word){
String [] Str=new String[100];
int n=0;
for (int from = 0; from < word.length(); from++) {
for (int to = from + 1; to <= word.length(); to++) {
str[n]=word.substring(from, to);
n++;
System.out.println(str[n]);
}
}
}
What is solution?
error is: cannot find symbol, variable str, loction: class substring
Well, that fairly clearly tells you what the error is: You haven't declared str. You have declared Str, but Java's identifiers are case sensitive, str and Str are not the same identifier.
So change
String [] Str=new String[100];
to
String [] str=new String[100];
// ^--- lower case
Before, when you hadn't said what the error was, there were a couple of other things Pshemo and I (amongst others) noticed:
You have a sequence issue here:
str[n]=word.substring(from, to);
n++;
System.out.println(str[n]);
...since you're incrementing n before outputting the string, you're always going to output null. Just moving the increment fixes that:
str[n]=word.substring(from, to);
System.out.println(str[n]);
n++;
Another possible problem can occur for longer words, where number of substrings can be more then 100. In that case you should avoid creating fixed size array, but try using dynamic size collection like List
List<String> str = new ArrayList<String>();
To put or read elements here just use str.add(substring) and str.get(index).

Categories

Resources