Why its gets error when my input string ends with spaces..? - java

// Count total no of words in String
class Word
{
static int Wordcount(String k)
{
int count=0;
char ch[]=k.toCharArray();
for(int i=0;i<k.length();i++)
{
if(ch[i]==32 && ch[i+1]!=32)
{
count++;
}
}
return(++count);
}
public static void main(String... s)
{
String k="java is a programming lan";
/* if input string is "java is a prog lan " then its gives//Exception
*/
int b=Wordcount(k);
System.out.println("Your input String has "+b +" words");
}
}
// Exception aati h agr string khtm ho ri h space se

if(ch[i]==32 && ch[i+1]!=32)
If ch[i] is the last character in the string, and the code tries to check ch[i+1], then you are outside the string's range, and you get an error.
If you want your condition to match spaces at the end of the string, then you can use
if (ch[i]==32 && (i+1 == ch.length || ch[i+1]!=32))
If you want your condition to match only if there is a non-space character after, then you can use
if (ch[i]==32 && i+1 < ch.length && ch[i+1]!=32)

You are checking the current index and the next index at the same time with this condition:
if(ch[i]==32 && ch[i+1]!=32)
If you are on the last character and it's a space, then ch[i+1]!=32 will be evaluated, causing the exception.
To resolve this, make sure you're not at the end of the array when checking index i+1.
if(ch[i]==32 && i < k.length() - 1 && ch[i+1]!=32)

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;
}

Can't figure out what is wrong with my code

This is the instructions i got from my teacher:
Write your code in the file WordCount.java. Your code should go into a method with the following signature. You may write your own main method to test your code. The graders will ignore your main method:
public static int countWords(String original, int minLength){}
Your method should count the number of words in the sentence that meet or exceed minLength (in letters). For example, if the minimum length given is 4, your program should only count words that are at least 4 letters long.
Words will be separated by one or more spaces. Non-letter characters (spaces, punctuation, digits, etc.) may be present, but should not count towards the length of words.
Hint: write a method that counts the number of letters (and ignores punctuation) in a string that holds a single word without spaces. In your countWords method, break the input string up into words and send each one to your method.
This is my code:
public class WordCount {
public static void main(String[] args)
{
System.out.print("Enter string: ");
String input = IO.readString();
System.out.print("Enter minimum length for letter: ");
int length = IO.readInt();
IO.outputIntAnswer(countWords(input, length));
}
public static int countWords(String original, int minLegth)
{
int count = 0;
int letterCount = 0;
for(int i = 0; i < original.length(); i++)
{
char temp = original.charAt(i);
if(temp >= 'A' && temp <= 'Z' || temp >= 'a' && temp <= 'z')
{
letterCount++;
}
else if(temp == ' '|| i == original.length()-1)
{
if(letterCount >= minLegth)
{
count++;
}
letterCount = 0;
}
}
return count;
}
}
My college uses an autograder to grade project and i am keep getting one of the test case wrong. Can someone help me figure out what the problem is?
I figured the problem that your code is not able to compare the last character.It expects a space after the last character so that it can compare the last character since java doesn't use null character terminator for string termination.I have emulated the same code using Scanner class as I was having some trouble with io.So I have done the following change:
Scanner sc1,sc2;
sc1=new Scanner(System.in);
String input = sc1.nextLine()+" ";
I don't know if its possible to do:
String input = IO.readString()+" ";
but i think you should try appending blank space " " at the end of the string

counting special characters in a user generated string

So I have this program that is supposed to to take any user generated string and display the amounts of white space, letters, numbers, and special characters. I do not want to duplicate a question. It seems to be a little more specific then talked about in other posts.
My error lies in the special characters. The specific error is return 0. I referenced stack overflow already in about every discussion they had on the matter. Which helped me form the special character method.
I have to keep the main method clear and call aforementioned methods
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
String userInput;
System.out.println("Please enter a string");
userInput = kbd.nextLine();
countletter(userInput);
countnumber(userInput);
countspecial(userInput);
countSpace(userInput);
}
public static void countletter(String userInput) {
int countletter = 0;
for (int i = 0; i < (userInput.length() - 1); i++) {
char location = userInput.charAt(i);
boolean x = Character.isLetter(location);
if (x) {
countletter++;
}
}
System.out.println("The number of Letters is: " + countletter);
}
public static void countnumber(String userInput) {
int countnumber = 0;
for (int i = 0; i < userInput.length() - 1; i++) {
char location = userInput.charAt(i);
boolean x = Character.isDigit(location);
if (x) {
countnumber++;
}
}
System.out.println("The number of digits is: " + countnumber);
}
public static void countSpace(String userInput) {
int countSpace = 0;
for (int i = 0; i < userInput.length() - 1; i++) {
char location = userInput.charAt(i);
boolean x = Character.isWhitespace(location);
if (x) {
countSpace++;
}
}
System.out.println("The number of white spaces is: " + countSpace);
}
public static void countspecial(String userInput) {
if (userInput == null || userInput.trim().isEmpty()) {
return 0;
}
int countSpecial = 0;
for (int i = 0; i < userInput.length(); i++) {
if (userInput.substring(i, 1).matches("[^A-Za-z0-9 ]")) {
countSpecial++;
}
}
System.out.println("The number of special chars is: " + countSpecial++);
}
}
My initial attempt at countSpecial:
public static void countspecial(String userInput) {
int countSpecial = 0;
for (int i = 0; i < (userInput.length() - 1); i++) {
if (userInput.substring(i, 1).matches("[^A-Za-z0-9]")) {
countSpecial++;
}
}
System.out.println("The number of special chars is: " + countSpecial++);
}
}
Where am I going wrong and why?
in your initial attemp you have problem with your substring
substring second parameter would be the index of your last character in the substring +1, and so you need to iterate until userInput.length() not userInput.length() -1.
And i dont know why would you increment the count after printing it , it actually does nothing but still makes no sense.
public static void countspecial(String userInput) {
if (userInput == null || userInput.trim().isEmpty()) {
return ;
}
int countSpecial = 0;
for (int i = 0; i < userInput.length(); i++) {
if (userInput.substring(i, i+1).matches("[^A-Za-z0-9]")) {
countSpecial++;
}
}
System.out.println("The number of special chars is: " + countSpecial);
}
A better way instead of subtring you could use "(userInput.charAt(i)+"").matches".
But a better solution would be counting all the digits and letters and subtract their sum form the total length of the string , this would give you the number of special characters as it is not recommended to use regex for simple requirement like this.
Look at the javadocs for substring.
Some languages that use a flavor of substring(int beginIndex, int length) where beginIndex is where you start the substring and length is how many characters are in the substring.
Java uses substring(int beginIndex, int endIndex) where beginIndex is where you start the substring and endIndex is the position of the ending character.
userInput.substring(i, 1);
Where i = 2 means you want to start the substring at index position 2 and end it at index position 1 and an exception is thrown.
If you're defining anything other than a letter, digit or whitespace character to be "special" then you should really test for it in the same way as the other tests so you don't miss anything because of different definitions of what constitutes a letter or digit. Character.isLetter() will return true for any Unicode letter, for example, not just ASCII A-Z or a-z. For consistency you should write:
char c = userInput.charAt(i);
if (!Character.isDigit(c) && !Character.isLetter(c) && !Character.isWhiteSpace(c)) {
countSpecial++;
}
But the problem in your original code is that the second parameter to String.substring() is the 'to' index, not a length. So if you were going to do with a regex it should be
if (userInput.substring(i, i+1).matches("[^A-Za-z0-9 ]")) {
countSpecial++;
}
Is this a practical example or are you asking for help doing an assignment? :-)
Even easier, don't loop. Just replace all non-special chars with nothing and count the length:
int countSpecial = userInput.replaceAll("[A-Za-z0-9\\s]", "").length();
You can apply this technique to all your character categories.

Java for loop isn't terminating in my code

For some reason my for loop is not terminating in my CapitalizeFirstSentence method. I set a breakpoint at that line and the condition (i != -1) is unmet, so the loop should terminate, but it doesn't!
It works when I use (i > 0) for the condition.
I'm not sure what's going on here.
import javax.swing.JOptionPane;
public class SentenceCapitalizer {
//Main Method
public static void main(String[] args) {
String input; //creates a String to hold keyboard input
//Prompt the user to enter a String using JOptionPane and set it equal to input
input = JOptionPane.showInputDialog("Enter a string. ");
//Display the new String with the first letter of each sentenced capitalized
JOptionPane.showMessageDialog(null, CapitalizeFirstSentence(input));
//Exit the program
System.exit(0);
}
//Capitalize first letter of each sentence
public static String CapitalizeFirstSentence(String in)
{
//Creates a StringBuilder object initiralized to the String argument "in"
StringBuilder temp = new StringBuilder(in);
//Capitalize first letter of the string if string length is > 0
if (temp.length() > 0)
{
temp.setCharAt(0, Character.toUpperCase(temp.charAt(0)));
}
//sets i equal to index of the space,
//keep capitalizing first letters of each sentence (loops each time it capitlizes a letter)
//until very end of the String
for (int i = temp.indexOf(". ")+1; i != -1; i++)
{
//Checks for extra spaces and moves index to first character of next sentence
while (i < temp.length() && temp.charAt(i) == ' ')
{
i++;
}
//Capitalize character
temp.setCharAt(i, Character.toUpperCase(temp.charAt(i)));
//Index the end of the sentence
i = temp.indexOf(". ", i);
}
//Convert temp to a String and return our new first-sentenced-capitalized String
return temp.toString();
}
}
First, it is not a good idea to modify the loop-controlling variable inside a for loop - it is quite hard to read and understand such code, and is prone to errors.
Now, to your example:
for (int i = temp.indexOf(". ")+1; i != -1; i++)
This means:
Initialize i to temp.indexOf(". ")+1, which is always >= 0
Terminate if i == -1
After each iteration, increment i by 1
So:
At the start, the cycle won't terminate because the initialization always returns >= 0
Each iteration, the loop body will set i = temp.indexOf(". ", i);, which is >= -1
After each iteration, i will be incremented by 1, so it will now be >= 0
As i is always >= 0, it will never meet the condition i == -1 and thus will never terminate
This line: for (int i = temp.indexOf(". ")+1; i != -1; i++) initializes i to be the result of indexOf + 1. IndexOf gives -1 if there is no hit, but you always add 1 to that during initialization, so it'll never be smaller than 0.
Using i > 0 seems perfectly fine there.

How to search a sub string in string

I tried this code but this is not working for all strings.
import java.util.Scanner;
public class Substring {
public static void main(String[] args) {
String str;
String subStr;
int count=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String : ");
str = in.nextLine();
System.out.println("Enter the Sub String : ");
subStr = in.nextLine();
for(int i =0 ; i <str.length(); i++)
{
if(str.charAt(i) == subStr.charAt(0))
{
for(int j=0 ; j<subStr.length();j++)
{
if( subStr.charAt(j) ==str.charAt(i+j))
count++;
else
{
count=0;
break;
}
}
}
}
if(count == subStr.length())
System.out.println("Sub String Matched !!");
else
System.out.println("String does not match !!");
}
}
What's wrong with this code ?
How to search a sub string in string
You don't need to loop over whole String. You can use string.indexOf(subString) to find the index of the substring in the string and it will return the index of the first occurrence of the substring. If you only want to ckeck whether String contains substring or not you can use string.contains(subString).
Try to decipher to the logic behind the code, so in plain english your code does the following:
LOGIC:
1)Enter a String via the Scanner and store it as str, do the same for the substring and store it as subStr.
2)Cycle through the each character of str via the for loop.
If the first character of the subStr is equal to any character with in str, then cycle through the characters of subStr. If the characters beyond this index are equal then increment the count variable each time the letters in each String are equal at the following indexes.
Else print String does not match.
3) If the number of similar characters in both Strings (denoted by the count variable) is equal to the length of the subString, then the subString is matched. Else no match.
ANSWER
So what went wrong?
I hope you notice on 2), The first bullet point you are only checking whether or not the first character of str is equal to the first character of subStr, if they are not equal you are then concluding that their is no match, which is false.
Consider the example:
str = "baloon"
subStr = "loon"
Your output would be: "String not matched"
This is because according to your code if 'b' != 'l' then theirs no match, which is false. That in essence is why your code does not work.
You could've just done the following:
if(str.contains(subStr)){
System.out.println("Sub-string matched");
}
Your code will only work if the substring is the end of the original string. This is because your code does not check that the entire substring was matched until it exits the first for loop. I moved the if (count == subStr.length() ) statement inside your first for loop and added a break if it finds the substring.
import java.util.Scanner;
public class Substring {
public static void main(String[] args) {
String str;
String subStr;
int count=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String : ");
str = in.nextLine();
System.out.println("Enter the Sub String : ");
subStr = in.nextLine();
for(int i =0 ; i <str.length(); i++) {
if(str.charAt(i) == subStr.charAt(0)) {
for(int j=0 ; j<subStr.length();j++) {
if( subStr.charAt(j) ==str.charAt(i+j)) {
count++;
} else {
count=0;
break;
}
}
if(count == subStr.length()) {
System.out.println("Sub String Matched !!");
//int index = i;
break;
}
}
}
if(count == 0){
System.out.println("String does not match !!");
}
}
}
Note: If you then want the index at which the substring (first) occurred, you can set int index = i; before breaking the loop as shown in the commented line above.
Another note: don't tend to omit the {}s in if and else statements. While, technically, you don't need them for single statements, it can cause bugs if you need to edit code later...

Categories