This program I'm making for a COSC course isn't compiling right, I keep getting the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.substring(String.java:1765)
at VowelCount.main(VowelCount.java:13)
Here's my code:
import java.util.Scanner;
public class VowelCount {
public static void main(String[] args) {
int a = 0, e = 0, i = 0, o = 0, u = 0, count = 0;
String input, letter;
Scanner scan = new Scanner (System.in);
System.out.println ("Please enter a string: ");
input = scan.nextLine();
while (count <= input.length() ) {
letter = input.substring(count, (count + 1));
if (letter == "a") {
a++; }
if (letter == "e") {
e++; }
if (letter == "i") {
i++; }
if (letter == "o") {
o++; }
if (letter == "u") {
u++; }
count++;
}
System.out.println ("There are " + a + " a's.");
System.out.println ("There are " + e + " e's.");
System.out.println ("There are " + i + " i's.");
System.out.println ("There are " + o + " o's.");
System.out.println ("There are " + u + " u's.");
}
}
To my knowledge this should work, but why doesn't it? Any help would be great. Thank you!
You may need to take out the = in the line
while (count <= input.length() ) {
and make it
while (count < input.length() ) {
because it is causing the substring to read beyond the length of the string.
===============
But I'll add a few extra bits of advice even though its not asked for:
do not use == to compare strings, use
letter.equals("a")
instead. Or even better, try using
char c = input.charAt(count);
to get the current character then compare like this:
c == 'a'
I think your loop condition should be count < input.length. Right now, the last iteration runs with count == length, so your substring call is given a start index after the last character in the string, which is illegal. These type of boundary errors are very common when writing such loops, so it's always good to double- and triple-check your loop conditions when you encounter a bug like this.
Also, comparing strings with the == operator usually won't do what you want. That compares whether or not the two variables reference the same object. Instead, you want to test string1.equals(string2), which compares the contents of the two strings.
Removing the equal sign should fix that.
while (count < input.length()) {
and since you want to get a single character, you should do this:
substr(count,1)
because the 2nd parameter is actually length, not index.
Fixed it with help from everyone, and especially Vincent. Thank you! Runs wonderfully.
import java.util.Scanner;
public class VowelCount {
public static void main(String[] args) {
int a = 0, e = 0, i = 0, o = 0, u = 0, count = 0;
String input;
char letter;
Scanner scan = new Scanner (System.in);
System.out.print ("Please enter a string: ");
input = scan.nextLine();
while (count < input.length() ) {
letter = input.charAt (count);
if (letter == 'a')
a++;
if (letter == 'e')
e++;
if (letter == 'i')
i++;
if (letter == 'o')
o++;
if (letter == 'u')
u++;
count++;
}
System.out.println ("There are " + a + " a's.");
System.out.println ("There are " + e + " e's.");
System.out.println ("There are " + i + " i's.");
System.out.println ("There are " + o + " o's.");
System.out.println ("There are " + u + " u's.");
}
}
Before loop,try below
if(input.length()>0){
//you code
}
Related
Create a program that reads a string entered by the user and then determines and prints how many of each lowercase vowel (a, e, i, o, and u) appear in the entire string. Have a separate counter for each vowel. Also, count and print the number of non-vowel characters.
When I created my program, the vowels return fine, but the consonant values are always off. Say the user inputs "I am feeling very cold today", the program returns the value of consonants as 19 when it should return it as 14.
Could you take a look at my program and help me determine why the returned consonant value is always wrong?
package CharacterCount;
import java.util.Scanner;
public class CharacterCount {
public static void main(String[] args) {
int a = 0, e = 0, x = 0;
int o = 0, u = 0, consonant = 0;
String str;
try (Scanner scan = new Scanner (System.in)) {
System.out.println("Enter a string");
str = scan.nextLine();
}
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c== 'a' || c== 'A') a++;
else if (c== 'e' || c== 'E') e++;
else if (c== 'i' || c== 'I') x++;
else if (c== 'o' || c== 'O') o++;
else if (c== 'u' || c== 'U') u++;
else consonant++;
}
System.out.println("a: " + a + "\n" +
"e: " + e + "\n" +
"i: " + x + "\n" +
"o: " + o + "\n" +
"u: " + u + "\n" +
"consonants:" + consonant);
}
}
looks like your program would currently consider a space character as a consonant... so you need to check for the space before incrementing your consonant variable
The instructions for the assignment are:
In many methods of communication throughout the last century, from telegrams to SMS messages to tweets, there is a benefit to reducing message length: either the number of characters is limited or using more characters incurs extra cost. Your job in this assignment is to write a program which takes a message as a string and reduces the number of characters it uses in a set way.
The first thing your program will do is ask the user to type a message which will be stored as a String. If the message contains less than 10 characters the program should print “This doesn’t need shortening!” and finish.
Otherwise, the message should be immediately converted to lowercase as this will make processing much easier. The program should then create a string in which every vowel (a, e, i, o, and u) from the message is removed unless the vowel is at the very start of a word (i.e., it is preceded by a space or is the first letter of the message). The program should also remove every repeated non-vowel character (i.e., if a character appears several times in a row it should only appear once at that location).
Finally, the program should output the shortened message, the number of vowels removed, the number of repeated non-vowel characters removed, and how much shorter the shortened message is than the original message. The exact format in which the program should print this information is shown in the sample runs.
my code is:
import java.util.Scanner;
import java.lang.Math;
class Main {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Type the message to be shortened");
String message = scan.nextLine();
int messagelength = message.length();
String shortmsg = "";
int vowel = 0;
if (messagelength < 10)
{
System.out.print("\nThis doesn't need shortening!");
}
else
{
message = message.toLowerCase();
for(int i = 0; i < message.length(); i++)
{
if (i == 0)
{
shortmsg = "" + message.substring(0,1);
}
else
{
if(message.charAt(i - 1) != ' '){
if (
message.charAt(i) != 'a' &&
message.charAt(i) != 'e' &&
message.charAt(i) != 'o' &&
message.charAt(i) != 'u' &&
message.charAt(i) != 'i')
{
shortmsg += message.charAt(i);
}
else
{
vowel++;
}
}}
}
System.out.println("Shortened message: " + shortmsg);
System.out.println("Vowels removed: " + vowel);
System.out.println("Total characters saved: " + vowel);
}}}
when I put in "Please shorten this message" the output is "Shortened message: pls hrtn hs ssg"
I have been working on this assignment for days and I am failing the class because of it can someone please guide me to the correct answer.
Thanks for your help.
import java.util.Scanner;
import java.lang.Math;
class Main{
public static void main (String str[]){
Scanner scan = new Scanner(System.in);
System.out.println("Type the message to be shortened.");
String message = scan.nextLine();
int messageLength = message.length();
int messageVowels = 0;
String newMessage = "";
int repeat = 0;
int total = 0;
if (messageLength < 10) {
System.out.println("This doesn't need shortening!");
} else {
message = message.toLowerCase();
newMessage = newMessage + message.charAt(0);
for (int i = 1; i < messageLength; i++) {
if (message.charAt(i)== 'a' ||
message.charAt(i)== 'e' ||
message.charAt(i)== 'i' ||
message.charAt(i)== 'o' ||
message.charAt(i)== 'u') {
if (message.charAt(i-1) == ' '){
newMessage = newMessage + message.charAt(i);
}
else {
messageVowels++;
}
} else {
if (message.charAt(i) != message.charAt(i-1)) {
newMessage = newMessage + message.charAt(i);
}
else {
repeat++;
}
}
}
total = repeat + messageVowels;
System.out.println("Shortened message: " + newMessage);
System.out.println("Repeated letters removed: " + repeat);
System.out.println("Vowels removed: " + messageVowels);
System.out.println("Total characters saved: " + total);
}
}
}
I'm having a problem with some code that I'm doing for homework where it won't repeat when I enter the word for the second time. I'm fairly new to Java so any help would be appreciated. Thanks
class Main
{
public static void main( String args[] )
{
System.out.print( "#Please enter a word : " );
String word = BIO.getString();
int i, length, vowels = 0;
String j;
length = word.length();
for (i = 0; i < length; i++)
{
j = word.substring(i, i + 1);
if (j.equalsIgnoreCase("a") == true)
vowels++;
else if (j.equalsIgnoreCase("e") == true)
vowels++;
else if (j.equalsIgnoreCase("i") == true)
vowels++;
else if (j.equalsIgnoreCase("o") == true)
vowels++;
else if (j.equalsIgnoreCase("u") == true)
vowels++;
}
System.out.print("[ " + vowels + "] vowels in " + "\""+word+"\"");
System.out.print("\n");
System.out.print("#Please enter a word : ");
word = BIO.getString();
}
}
To get the result you expect, you should nest your code inside a loop. Like this:
class Main
{
public static void main( String args[] )
{
System.out.print( "#Please enter a word : " );
String word = BIO.getString();
while(!word.equals("QUIT")){
int i, length, vowels = 0;
String j;
length = word.length();
for (i = 0; i < length; i++)
{
j = word.substring(i, i + 1);
if (j.equalsIgnoreCase("a") == true)
vowels++;
else if (j.equalsIgnoreCase("e") == true)
vowels++;
else if (j.equalsIgnoreCase("i") == true)
vowels++;
else if (j.equalsIgnoreCase("o") == true)
vowels++;
else if (j.equalsIgnoreCase("u") == true)
vowels++;
}
System.out.print("[ " + vowels + "] vowels in " + "\""+word+"\"");
System.out.print("\n");
System.out.print("#Please enter a word : ");
word = BIO.getString();
}
}
That way, your code will loop until you enter the word QUIT.
After the second input executes the program terminates. Use a while(true) block with some sort of special input (like "quit" or an empty string) to break the loop.
Do while loop is the best way to achieve what you want to here ! As mentioned above, you have not included your
System.out.print("#Please enter a word : ");
word = BIO.getString();
part in any type of loop. SO you can't expect the code to run otherwise. Include it in a do-while and you should be doing well. A well modified example is already answered above.
I get this error when I try to repeat the code.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
Type a sentence and this program will tell you
how many vowels there are (excluding 'y'):
at java.lang.String.substring(String.java:1934)
at countvowels.Main.main(Main.java:53)
Java Result: 1
Here is my code:
Scanner input = new Scanner(System.in);
int answer = 0;
System.out.println("Count Vowels \n============");
// the do-while loop makes sure that the code is executed at least once
do {
if(answer == 1) {
System.out.println("You have chosen to count the vowels in another phrase");
}
System.out.println("Type a sentence and this program will tell you\nhow many vowels there are (excluding 'y'):");
String string1;
string1 = input.nextLine();
string1 = string1.toLowerCase();
int vowels=0;
int i = 0;
for (String Vowels : string1.split(" ")) {
for (i = 0; i < Vowels.length(); i++) {
int letter = Vowels.charAt(i);
if (letter == 'a' || letter == 'e' || letter == 'i'
|| letter == 'o' || letter == 'u') {
vowels++;
}
}
System.out.println(Vowels.substring(0,1)
+ Vowels.substring(1) + " has " + vowels + " vowels");
vowels = 0;
}
System.out.println("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press 2");
} while(input.nextInt() == 1);
System.out.println("Have a nice day");
}
}
I suspect you are getting this exception, when you have a word that contains just a single character. To eliminate this, and to also enhance your code, I would replace this line:
System.out.println(Vowels.substring(0,1) + Vowels.substring(1) + " has " + vowels + " vowels");
with:
System.out.println(Vowels + " has " + vowels + " vowels");
Also, modify the loop ending with the following:
nextInt(), reads just the next integer value.. So the line breaker stays in the buffer, and is later processed by the nextLine() command.
Modify your loop ending with the following:
answer = input.nextInt();
input.nextLine();
}
while (answer == 1);
I think your error come from your use of charAt()
This exception is thrown when the index is equal to the size of the string.
I have to create a program that accepts a "tweet" from a user and validates it. First it tests to make sure it is less than 140 characters.
If it is valid, it counts the number of hashtags (#), attribution symbols (#), and links ("http://) are in the string, then prints them out. My program works for hashtags and attributions, but not links. How can I fix this code so that it works?
import java.util.Scanner;
class Testing {
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;
if (length > 140) {
System.out.println("Excess characters: " + (length - 140));
} else {
while (count < length) {
letter = input.charAt(count);
if (letter =='#') {
hashtags++;
count++;
}
if (letter == '#') {
attributions++;
count++;
}
if (letter == 'h') {
String test = input.substring(count,count+6);
test = test.toLowerCase();
if (test == "http://") {
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);
}
}
I think your code will not work with link like http://test.com/ingex.php?p=1#section. Use regular expressions instead of if () else {} if () else {}. And keep in mind: there is no token(mention, hashtag, link) which contains other token.
import java.util.Scanner;
class Testing
{
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;
if (length > 140)
{
System.out.println("Excess characters: " + (length - 140));
}
else
{
while (count < length)
{
letter = input.charAt(count);
if (letter =='#')
{
hashtags ++;
count ++;
}
if (letter == '#')
{
attributions ++;
count ++;
}
if (letter == 'h')
{
//String test = input.substring(count,count+6);
//test = test.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);
}
}
}
I changed your code in a few ways, the biggest being that instead of the == you had for checking if the links start with "http://". I also used startsWith(String s, int index) because like #Robin said, anything starting with an h would probably mess up your program.
I also used count to specify where it should start, basically the index part of you parameter
You may find additional functions and documentation in the Strings class javadoc of use.