I'm trying to make this program to count the number of consecutive characters
and I'm getting the error that says:
"String index out of range."
import javax.swing.*;
public class Project0 {
public static void main(String[] args){
String sentence;
sentence = JOptionPane.showInputDialog(null, "Enter a sentence:"); /*Asks the user to
enter a sentence*/
int pairs = 0;
for (int i = 0; i < sentence.length(); i++){ //counts the pairs of consecutive characters
if ( sentence.charAt(i) == sentence.charAt(i+1)) pairs++;
}
JOptionPane.showMessageDialog(null, "There were " + pairs + " pairs of consecutive characters");
}//main
}// Project0
The last element in your loop is 100% guaranteed to cause a problem. Perhaps only go to the length - 1 in your loop?
Consider the code:
for (int i = 0; i < sentence.length(); i++){
if ( sentence.charAt(i) == sentence.charAt(i+1)) pairs++;
}
String s = "AABBCC";
first loop, i = 0 : compare s[0] to s[1]
first loop, i = 1 : compare s[1] to s[2]
first loop, i = 2 : compare s[2] to s[3]
first loop, i = 3 : compare s[3] to s[4]
first loop, i = 4 : compare s[4] to s[5]
first loop, i = 5 : compare s[5] to s[6] // WOAH, you can't do that! there is no s[6]!!
sentence.charAt(i+1) will cause this as i + 1 > sentence.length() at the last step of the for-loop
You need to change the upper limit of your for loop to not go all the way to the end because the way you look for consecutive characters is "look at the ith character, and then look at the next
one". Once you get to the end, there is no "next one", so just stop at the next to last one.
for (int i = 0; i < sentence.length()-1; i++)
Related
import java.util.ArrayList;
import java.util.List;
class Scratch {
public static void main(String[] args) {
List<String> Numbers = new ArrayList<>();
Numbers.add("1");
Numbers.add("2");
Numbers.add("3");
Numbers.add("4");
Numbers.add("5");
Numbers.add("6");
System.out.println(Numbers);
for(int i = 0; i < Numbers.size(); i++){
for(int j = 0; Numbers.size() == 2; j++)
System.out.println(Numbers);
}
}
}
I am having trouble doing the logic where I have 6 numbers in my arraylist and I want to print each 2 elements then go the next elements by 2. Like to print 1, 2 then 3, 4 then 5, 6.
for(int i = 0; i < Numbers.size(); i+=2){
System.out.print(Numbers.get(i));
if(i<Numbers.size()-1) {
System.out.print(" " + Numbers.get(i+1));
}
System.out.println();
}
Go in steps of 2 i+=2.
Then print the first number using System.out.print() which will not print a newline.
Then check whether there is a second number to be displayed if(i<Numbers.size()-1) and if there is print it separated by a space (or whatever you like).
And then the System.out.println() will just print the newline.
You can use the conditional operator to determine when to print a new line:
for(int i = 0; i < Numbers.size(); i++) {
System.out.print(Numbers.get(i) + (i % 2 == 1 || i == Numbers.size()-1 ? "\n" : ", "));
}
For every even index and for the last element in the list, this will print a new line after the element. And for every odd index, a trailing comma would be printed.
Make life easy and use an iterator. You don't want to juggle with indexes too much as it obfuscates your code.
Iterator<String> iterator = numbers.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next() + "," + (iterator.hasNext() ? iterator.next() : ""));
}
The following is my code:
char[] array = new char[26] ;
int index = 0 ;
int letter = 0 ;
int countA = 0 ;
String sentence = "Once upon a time..." ;
if(sentence.contains("."))
{
String sentenceNoSpace = sentence.replace(" ", "").toLowerCase() ;
String sentenceFinal = sentenceNoSpace.substring(0, sentenceNoSpace.indexOf(".")) ;
char[] count = new char[sentenceFinal.length()] ;
for (char c = 'a'; c <= 'z'; c++)
{
array[index++] = c ;
for(int i = 0; i < sentenceFinal.length(); i++)
{
if(sentenceFinal.charAt(i) == c)
count[letter++] = c ;
//if(sentenceFinal.charAt(i) == 'a')
//countA++ ;
}
}
String result = new String(count) ; // Convert to a string.
System.out.println("\n" + result) ;
System.out.println("\nTotal number of letters is " + result.length()) ;
System.out.println(countA) ;
}
else
{
System.out.println("You forgot a period. Try again.") ;
}
I am having trouble counting how many a's, b's, c's, etc. are in a given sentence. There is one way I can do it and it is this part
//if(sentenceFinal.charAt(i) == 'a')
//countA++ ;
which I can just create all the way to z. Is there a more efficient way?
Note: No using Hashmap or any other advance techniques.
There is no need of eliminating spaces. This is just additional work you're doing.
int countOfLetters = 0 ;
String sentence = "Once upon a time..." ;
sentence = sentence.toLowerCase();
int[] countOfAlphabets = new int[26];
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) >= 'a' && sentence.charAt(i) <= 'z') {
countOfAlphabets[sentence.charAt(i) - 97]++;
countOfLetters++;
}
}
So, countOfLetters will give you the total count of letters.
If you want individual count, suppose for example, you want count of 'c',
You can get it by accessing countOfAlphabets array like countOfAlphabets['c' - 97] (97 being the ASCII value of 'a')
Use an int array letterCounts that will store the counts for each letter. Assuming the case of the letters can be ignored, the length of the letterCounts array will be 26.
Iterate over the string's characters and update the corresponding integer in the array. Use its ASCII value to find the corresponding index, as follows.
letterCounts[c - 97]++
97 is the ASCII value of 'a', whose count needs to be stored at index 0.
In this way, subtracting 97 from the character's ASCII value will give the corresponding index for that character.
Note: This is assuming that you want to store the counts for lowercase letters.
Pretty fiddly without using maps, but this will count all characters in a string.
You might want to modify to exclude things like spaces etc.
public class Main {
public static void main(String[] args) {
String sentence = "Once upon a time...";
// Create an array of size 256 ASCII_SIZE
int count[] = new int[256];
int length = sentence.length();
// Initialize count array index
for (int i = 0; i < length; i++)
count[sentence.charAt(i)]++;
// Create an array of given String size
char chars[] = new char[sentence.length()];
for (int i = 0; i < length; i++) {
chars[i] = sentence.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if (sentence.charAt(i) == chars[j])
find++;
}
if (find == 1) {
System.out.println("Occurrence of " + sentence.charAt(i) + " is:" + count[sentence.charAt(i)]);
}
}
}
}
Which outputs:
Occurrence of O is:1
Occurrence of n is:2
Occurrence of c is:1
Occurrence of e is:2
Occurrence of is:3
Occurrence of u is:1
Occurrence of p is:1
Occurrence of o is:1
Occurrence of a is:1
Occurrence of t is:1
Occurrence of i is:1
Occurrence of m is:1
Occurrence of . is:3
Check Below code You can have a 26 length array and index will increment according to the presence of the alphabet.
public void getResult(){
int [] charCount = new int [26];
int countA = 0 ;
String sentence = "Once upon a time..." ;
if(sentence.contains("."))
{
String sentenceNoSpace = sentence.replace(" ", "").toLowerCase() ;
String sentenceFinal = sentenceNoSpace.substring(0, sentenceNoSpace.indexOf(".")) ;
char[] sentenceCharArray = sentenceFinal.toCharArray();
//char a = 97;
for (int i = 0; i <sentenceCharArray.length ; i++) {
int index = sentenceCharArray[i] - 97 ;
if(index >= 0 && index <= 26) {
charCount[index] += 1;
}
}
System.out.print("Result : ");
for (int i = 0; i < charCount.length ; i++) {
System.out.print(charCount [i]+" , ");
}
System.out.println("\nTotal number of letters is " + sentenceCharArray.length) ;
}
else
{
System.out.println("You forgot a period. Try again.") ;
}
}
Since there are 26 letters in the US alphabet, you can use an int[] with a size of 26
int[] letterCount = new int[26];
to hold the count of each letter where index 0 represents 'a', 1 represents 'b', etc...
As you traverse through the sentence, check if the character you're on is a letter, Character.isLetter(), then increment the element in the array that represents the letter.
letterCount[letter - 'a']++;
We subtract 'a' from the letter to give us the correct index.
Code Sample
package stackoverflow;
public class Question {
public static void main(String[] args) {
String sentence = "The quick brown fox jumps over the lazy dog.";
int[] letterCount = new int[26];
if (sentence.contains(".")) {
// toLowerCase() the sentence since we count upper and lowercase as the same
for (char letter : sentence.toLowerCase().toCharArray()) {
if (Character.isLetter(letter)) {
letterCount[letter - 'a']++;
}
}
// Display the count of each letter that was found
int sumOfLetters = 0;
for (int i = 0; i < letterCount.length; i++) {
int count = letterCount[i];
if (count > 0) {
System.out.println((char)(i + 'a') + " occurs " + count + " times");
sumOfLetters += count;
}
}
System.out.println("Total number of letters is " + sumOfLetters);
} else {
System.out.println("You forgot a period. Try again.");
}
}
}
Result
a occurs 1 times
b occurs 1 times
c occurs 1 times
d occurs 1 times
e occurs 3 times
f occurs 1 times
g occurs 1 times
h occurs 2 times
i occurs 1 times
j occurs 1 times
k occurs 1 times
l occurs 1 times
m occurs 1 times
n occurs 1 times
o occurs 4 times
p occurs 1 times
q occurs 1 times
r occurs 2 times
s occurs 1 times
t occurs 2 times
u occurs 2 times
v occurs 1 times
w occurs 1 times
x occurs 1 times
y occurs 1 times
z occurs 1 times
Total number of letters is 35
Rebuttal Question
What is wrong with using Java 8 and using the chars() of a String? With it, you can accomplish the same thing with less code. For the total number of letters, we just use String.replaceAll() and remove all non-letters from the String with the pattern [^A-Za-z]and use the length() of the result.
package stackoverflow;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Question {
public static void main(String[] args) {
String sentence = "The quick brown fox jumps over the lazy dog.";
System.out.println(sentence.toLowerCase().chars()
// Change the IntStream to a stream of Characters
.mapToObj(c -> (char)c)
// Filter out non lower case letters
.filter(c -> 'a' <= c && c <= 'z')
// Collect up the letters and count them
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())));
System.out.println("Total letter count is " + sentence.replaceAll("[^A-Za-z]", "").length());
}
}
Result
{a=1, b=1, c=1, d=1, e=3, f=1, g=1, h=2, i=1, j=1, k=1, l=1, m=1, n=1, o=4, p=1, q=1, r=2, s=1, t=2, u=2, v=1, w=1, x=1, y=1, z=1}
Total letter count is 35
You can solve it with Regex If Regex wont be considered as High-tech 🙂
Idea is simple: Remove all letters and subtract output from original string length to get counter
String sentence = "Once upon a time...";
String noLetterString = sentence.replaceAll("[a-zA-Z]", "");
int counterLetter = sentence.length() - noLetterString.length();
System.out.println("counter:" + counterLetter);
By old school programming 🙂
Idea here is in reverse, appending only letters
String sentence = "Once upon a time...";
String lowerCase = sentence.toLowerCase(); // to avoid comparison to UpperCase letters
StringBuilder counterStr = new StringBuilder();
for (char l : lowerCase.toCharArray()) {
if (l >= 'a' && l <= 'z') {
counterStr.append(l);
}
}
System.out.println("counterStr:" + counterStr);
System.out.println("counter:" + counterStr.length());
Here is the Update Code :
int[] array = new int[26] ;
String sentence = "Once upon a time..." ;
if(sentence.contains("."))
{
String sentenceNoSpace = sentence.replace(" ", "").toLowerCase() ;
String sentenceFinal = sentenceNoSpace.substring(0, sentenceNoSpace.indexOf(".")) ;
for (char c : sentenceFinal.toCharArray())
{
System.out.println(c+" "+(c-97));
array[c-97] += 1;
}
// System.out.println("\n" + Arrays.toString(array)) ;
for(int i=0; i< array.length;i++) {
if(array[i] != 0) {
char c = (char)(i+97);
System.out.println(c+" occured "+ array[i]+" times");
}
}
}
else
{
System.out.println("You forgot a period. Try again.") ;
}
I am currently taking Programming 1 and learning Java. Here is my assignment...
Ask user to enter a number and then in a loop, find any 2 numbers that they are the same and next to each other. And then display the number in the loop. For example, if user enters 133455662, the program displays 356. For simplicity, assume user never will enter all three numbers the same and next to each other
Here is the code I've come up with, except I keep getting an error...
public static void main(String[] args){
String num = "";
String result = "";
System.out.println("Enter a number");
Scanner s = new Scanner(System.in);
num = s.next();
int len = num.length();
for(int n = 0;n<len;n++){
char c = num.charAt(n);
char c2 = num.charAt(n+1);
if(c == c2){
result = result + c;
}
}
System.out.println(num);
}
This is the error I get...
run: Enter a number 001123455 Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range:
9 at java.lang.String.charAt(String.java:658) at
CS120_Labs.Homework09_C.main(Homework09_C.java:18)
C:\Users\Fletcher\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
Java returned: 1 BUILD FAILED (total time: 6 seconds)
Thanks again for anyone that can help!
Exception said that StringIndexOutOfBoundsException, so you need two changes to make it work:
Add "-1" to fix error "for (int n = 0; n < len - 1; n++) {"
And also at the end of the program you need change from "num" to "result" System.out.println(result);
public static void main(String[] args) {
String num = "";
String result = "";
System.out.println("Enter a number");
Scanner s = new Scanner(System.in);
num = s.next();
int len = num.length();
for (int n = 0; n < len - 1; n++) {
char c = num.charAt(n);
char c2 = num.charAt(n + 1);
if (c == c2) {
result = result + c;
}
}
System.out.println(result);
}
I think all you need to do is to change your for line like (updated to len-1):
for(int n = 0; n<len-1; n++){
...
}
Change your for loop as
for(int n = 0; n < len - 1; n++)
since you are looking up the character at index n and len+1 in the for-loop body, you should loop from 0 to len-1
In addition to the other answers here that just "give" you the solution, I wanted to add:
This is a common problem when you first start out using structures that are "0" indexed. For example, if we have the letters A-I:
0 1 2 3 4 5 6 7 8
A B C D E F G H I
There are 9 letters there, so length() will return 9. The problem is, the letter at the first position isn't 1, it's 0. If in a loop you count all the way up to 9, the last iteration of the loop's charAt line will say "Take the character at position 9" but 9 is out of range of available positions, hence the exception String index out of range: 9.
This can happen anytime you are referencing an object in a structure that has positional indexes. When you see an exception like this, the first thing to check is why did my code try to access an index that didn't exist. In this case, the answer is the upper bound of the for loop. There are other possibilities; for example, your index variable (in this case i) is modified inside the loop, or if the lower bound is negative.
My code below is giving the following error and I can't figure out why. I am trying to reorder the entered word ("Polish" for example) in the order of:
(First letter, last letter, second letter, second last letter, third letter... so on) so the output should be "Phosli".
Updated code
public static String encodeTheWord(String word1)
{
int b = 0;
int e = word1.length()-1;
String word2 = "";
for (int i=0; i<e; i++)
{
word2 = word2 + word1.charAt(b) + word1.charAt(e);
b+=1;
e-=1;
}
System.out.println(word2);
return (word2);
}
For a word with an even amount of characters (Polish), the order of the characters becomes 051423, so the maximum value of b is 2 and the minimum value is e is from 5 to 3. Thus, your loop should decrement e and increment b twice (so you run the loop for word1.length() / 2 times). Also,
int e = word1.length();
Would need to be:
int e = word1.length() - 1;
For words of an uneven length (word1.length() % 2 > 0) you need an extra check or you will repeat the middle character.
your for loop is wrong, you can get a char at index 0, until the word1.length()-1...
must be
for (int i=0; i<word1.length()-1; i++)
the same applies for this...
word1.charAt(e);
because you defined e as word1.length()
Given a non-empty string str like "Code" print a string like "CCoCodCode". Where at each index in the string you have to reprint the string up to that index.
I know there is DEFINITELY something wrong with this code that I wrote because the answer should be CCoCodCode, but instead it's giving me the alphabet! I don't know how I should change it.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String str = scan.next();
int x = str.length();
for(char i = str.charAt(0); i <= str.charAt(x-1); i++)
{
System.out.print(i);
}
}
The char datatype can be treated as a number; you can increment it and manipulate it as a number.
What you really want is successive substrings of str to be printed. Loop over an int that will represent the ending position of the substring to be printed.
for (int i = 0; i < str.length(); i++)
{
System.out.print(str.substring(0, i + 1));
}
The end index argument to substring is exclusive, which is why I added 1.
Let's say that str is "Code". We can perform some mental substitutions to see what happens to your loop.
str is "Code"
x is 4
str.charAt(0) is 'C'
str.charAt(x-1) is 'e'
Making these substitutions, your loop is:
for(char i = 'C'; i <= 'e'; i++)
{
System.out.print(i);
}
Does this help you see the problem? I would think you'd have a loop from 0 to 3, not from 'C' to 'e'...
Many ways to get it done, suppose we have the input from user stored in a string named "c"... then...
String c = "Code";
for (int i = 0; i < c.length(); i++) {
System.out.print(c.substring(0, i));
}
System.out.print(c);
And this will print the sequence you are looking for.
It is outputting the alphabet because you are printing the counter instead of the characters in the string!
As it is, the first iteration of the for loop will set i to the first character, print that, then the operation i++ will increment i by one. Wait, so if the first character is "C", so i = 'C', what is i++?
Well it turns out characters can be represented by numbers. For example, 'C' has a value of 67. So incrementing it makes it 68, which represents 'D'. So if you run the loop on "Code", it will increment your counter 4 times, giving "CDEF". If you run on "Codecodecode", that will make the loop run 12 times, giving "CDEFGHIJKLMN".
What you really want is to loop through the string by its index instead:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str = scan.next();
int length = str.length();
for (int i = 0; i < length; i++) {
System.out.print(str.substring(0, i + 1));
}
}