java StringIndexOutOfBoundsException: String index out of range: 0 - java

Its a very simple function. I don't know why it is giving an StringIndexOutOfBoundsException for the function source.charAt(i). I have checked the values of 'i' are not exceeding the length of the string which will be always 9.
public static String getClockResetString(String source, String target, Hashtable order)
{
String temp = "",name;
for(int i = 0; i < source.length(); i++){
name = (String)order.get(""+i);
if(source.charAt(i) != target.charAt(i))
{
if((int)source.charAt(i) < (int)target.charAt(i)){
temp = "h" + name + "=" + "dp" + name + "0" + " do " + "{h" + name + "'=0, k'=k+1} ";
}
else{
temp = "h" + name + "=" + "dn" + name + "1" + " do " + "{h" + name + "'=0, k'=k+1} ";
}
}
}
return temp;
}

I bet that you are exceeding the bounds on target, not source
if(source.charAt(i) != target.charAt(i))
You need to check that
i < target.length()

Related

Displaying number of times a character is in a string

I need to print the amount of times an input character appears in the string. It runs and works for all tests, however when a character appears only 1 time it prints "1 times" instead of "1 time" like expected, and i am unsure of how to add this into my code. It has to be when count is equal to 1 the outprint changes from times to time. I am lost.
for( i = 0; i < input.length(); i ++){
if (input.charAt(i) == letter)
{
count = count + 1;
}
}
System.out.println("The letter '" + letter + "' appears " + count + " times in the string " + "\"" + input + ".\"");
Expected to
You should add a condition for the same instead of printing the static string "times" as below:
for( i = 0; i < input.length(); i ++){
if (input.charAt(i) == letter)
{
count = count + 1;
}
}
String str = (count==1)?"time":"times";
System.out.println("The letter '" + letter + "' appears " + count + str + " in the string " + "\"" + input + ".\"");
Maybe try something like this
String plural = (count == 1) ? "" : "s";
System.out.println("The letter '" + letter + "' appears " + count + " time" + plural + "in the string " + "\"" + input + ".\"");
I would use an if statement to determine how many times this specific letter appears in your string. Also, since first character is charAt(0), the last character should be charAt(s.length()-1);.
for( i = 0; i < (input.length()-1); i ++){
if (input.charAt(i) == letter)
count = count + 1;
} //end of your for loop
if (count == 1){
System.out.println("The letter '" + letter +
"' appears " + count + " time in the string " + "\"" + input + ".\"");
}
else{
System.out.println("The letter '" + letter + "' appears " + count + " times in the string " + "\"" + input + ".\"");
}

Error on the for loop - trying to use loop to count the repetition of letter

On the for loop I have the Java applet is showing me that I have an error. I am trying to use the for loop to count the repetition of letter.
String countString = "";
for (int i = 0; i < 26; i++){
// at the line below, my java applet says I have an error, and that the
//"letterCounts" should be a int and not a string, but I need it to be a string
String n = letterCounts[i];
if (n.equals("0")) {
countString = countString + " ";
} else if (n.length() == 1) {
countString = countString + " " + n + " ";
} else {
countString = countString + n + " ";
}
}
this.countLabel.setText(countString);
You donot show the definition of letterCounts, but I bet it is int[] letterCounts.
So since letterCounts is an array of int, you cannot just assign it to a String.
Just change String n to int n and your comparison to n == 0 and it should work. See below:
String countString = "";
for (int i = 0; i < 26; i++)
{
int n = letterCounts[i];
if (n == 0) {
countString = countString + " ";
} else if (n < 10) {
countString = countString + " " + n + " ";
} else {
countString = countString + n + " ";
}
}
this.countLabel.setText(countString);

returning ArrayIndexOutOfBoundsException error for unknown reason

I am trying to create a basic bubble sort program but at some point the array tries to reference the 11th position despite the array being 10 long and i am not sure when it occurs
int Last, i = 0, Temp;
int[] Numbers = new int[10];
String[] NumbersString = new String[10];
String initialString = TextBox.getText();
NumbersString = initialString.split(" ");
while(i<10){
Numbers[i] = Integer.parseInt(NumbersString[i]);
i = i + 1;
}
Last = 9;
Boolean Swapped = true;
while(Swapped = true) {
Swapped = false;
i = 0;
while(i < Last) {
if(Numbers[i] > Numbers[i+1]){
Temp = Numbers[i];
Numbers[i] = Numbers[i+1];
Numbers[i+1] = Temp;
Swapped = true;
}
i = i + 1;
}
Last = Last-1;
}
String Result = Numbers[0] + " " + Numbers[1] + " " + Numbers[2] + " " + Numbers[3] + " " + Numbers[4] + " " + Numbers[5] + " " + Numbers[6] + " " + Numbers[7] + " " + Numbers[8] + " " + Numbers[9];
ResultText.setText(Result);
change
while(Swapped = true) {
to
while(Swapped == true) {
What is happening is that Last is firstly wrapping to Negative and then when it gets to the minimum negative number it wraps to Integer.MAX_VALUE and then i will exceed 9
just try to put the length of the Array in here.
int Last, i = 0, Temp;
int[] Numbers = new int[10];
String[] NumbersString = new String[10];
String initialString = "1";
NumbersString = initialString.split(" ");
while (i < NumbersString.length) { // <-- I change it to NumbersString.length
Numbers[i] = Integer.parseInt(NumbersString[i]);
i = i + 1;
}
Last = Numbers.length-1; // <-- I change it to Numbers.length-1
Boolean Swapped = true;
while (Swapped) { // <-- I change it to Swapped only because your Swapped is a Boolean type, no need to equals it into true.
Swapped = false;
i = 0;
while (i < Last) {
if (Numbers[i] > Numbers[i + 1]) {
Temp = Numbers[i];
Numbers[i] = Numbers[i + 1];
Numbers[i + 1] = Temp;
Swapped = true;
}
i = i + 1;
}
Last = Last - 1;
}
String Result = Numbers[0] + " " + Numbers[1] + " " + Numbers[2] + " " + Numbers[3] + " " + Numbers[4] + " "
+ Numbers[5] + " " + Numbers[6] + " " + Numbers[7] + " " + Numbers[8] + " " + Numbers[9];
System.out.println(Result);
}

Java String letter counter not working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
This is my code for a program that should count the number of each letter in an inputted string. When I run the program, it says that there is 0 of each letter, no matter what I input. Thanks for the help in advance!
import java.util.Scanner;
public class stringprogram {
public static void stringinputmethod()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String");
String strs = scan.nextLine();
int strslength = strs.length();
int numa = 0;
int numb = 0;
int numc = 0;
int numd = 0;
int nume = 0;
int numf = 0;
int numg = 0;
int numh = 0;
int numi = 0;
int numj = 0;
int numk = 0;
int numl = 0;
int numm = 0;
int numn = 0;
int numo = 0;
int nump = 0;
int numq = 0;
int numr = 0;
int nums = 0;
int numt = 0;
int numu = 0;
int numv = 0;
int numw = 0;
int numx = 0;
int numy = 0;
int numz = 0;
for(int i = 0; i <= strslength; i++)
{
if (strs.substring(i, i) == "a")
{
numa = numa + 1;
}
if (strs.substring(i, i) == "b")
{
numb = numb + 1;
}
if (strs.substring(i, i) == "c")
{
numc = numc + 1;
}
if (strs.substring(i, i) == "d")
{
numd = numd + 1;
}
if (strs.substring(i, i) == "e")
{
nume = nume + 1;
}
if (strs.substring(i, i) == "f")
{
numf = numf + 1;
}
if (strs.substring(i, i) == "g")
{
numg = numg + 1;
}
if (strs.substring(i, i) == "h")
{
numh = numh + 1;
}
if (strs.substring(i, i) == "i")
{
numi = numi + 1;
}
if (strs.substring(i, i) == "j")
{
numj = numj + 1;
}
if (strs.substring(i, i) == "k")
{
numk = numk + 1;
}
if (strs.substring(i, i) == "l")
{
numl = numl + 1;
}
if (strs.substring(i, i) == "m")
{
numm = numm + 1;
}
if (strs.substring(i, i) == "n")
{
numn = numn + 1;
}
if (strs.substring(i, i) == "o")
{
numo = numo + 1;
}
if (strs.substring(i, i) == "p")
{
nump = nump + 1;
}
if (strs.substring(i, i) == "q")
{
numq = numq + 1;
}
if (strs.substring(i, i) == "r")
{
numr = numr + 1;
}
if (strs.substring(i, i) == "s")
{
nums = nums + 1;
}
if (strs.substring(i, i) == "t")
{
numt = numt + 1;
}
if (strs.substring(i, i) == "u")
{
numu = numu + 1;
}
if (strs.substring(i, i) == "v")
{
numv = numv + 1;
}
if (strs.substring(i, i) == "w")
{
numw = numw + 1;
}
if (strs.substring(i, i) == "x")
{
numx = numx + 1;
}
if (strs.substring(i, i) == "y")
{
numy = numy + 1;
}
if (strs.substring(i, i) == "z")
{
numz = numz + 1;
}
}
System.out.println("Number of a's: " + numa + "\n" + "Number of b's: " + numb + "\n" + "Number of c's: " + numc + "\n" + "Number of d's: " + numd + "\n" + "Number of e's: " + nume + "\n" + "Number of f's: " + numf + "\n" + "Number of g's: " + numg + "\n" + "Number of h's: " + numa + "\n" + "Number of i's: " + numi + "\n" + "Number of j's: " + numj + "\n" + "Number of k's: " + numk + "\n" + "Number of l's: " + numl + "\n" + "Number of m's: " + numm + "\n" + "Number of n's: " + numn + "\n" + "Number of o's: " + numo + "\n" + "Number of p's: " + nump + "\n" + "Number of q's: " + numq + "\n" + "Number of r's: " + numr + "\n" + "Number of s's: " + nums + "\n" + "Number of t's: " + numt + "\n" + "Number of u's: " + numu + "\n" + "Number of v's: " + numv + "\n" + "Number of w's: " + numw + "\n" + "Number of x's: " + numx + "\n" + "Number of y's: " + numy + "\n" + "Number of z's: " + numz);
}
public static void main(String[] args)
{
stringinputmethod();
}
}
Correct usage of the substring method:
strs.substring(i, i)
needs to be
strs.substring(i, i + 1)
because the char at lastIndex is not included in the output.
Correct comparison of Strings in Java
Also, as pointed out in the comments to this answer, you are comparing Strings with the == operator.
This will only works as long as both your Strings are the same object. For proper comparison you need to use strs.substring(..).equals()
Proper storing of data
Additionally, as already suggested in a comment to your question, you should start using arrays to save data like this.
Instead of
int numa = 0;
....
int numz = 0;
you should use arrays, or even better Map<Character,Integer>.
strs.substring(i, i) == "a" have two problems:
substring(i, i) creates string from i (inclusive), till i (exclusive) which means it creates empty string ""
this is not how we compare Strings. == may work sometimes if strings are pooled, but for dynamically created strings you need to use equals instead of == because Strings are objects, or even better use charAt(i) to get primitive char which you can be able to compare like strs.charAt(i) == 'a' (notice ' instead of ").
You can also use enhanced for loop on array of characters representing your string to avoid charAt. You should probably also be working on lower case characters as pointed in this comment. So your code can look more like
for (char ch : strs.toLowerCase().toCharArray()){
//do something based on value of `ch`
}
Try this:
It is a little bit shorter than your implementation (which is very good, but still a little bit verbose). Use Java 8 with this code, otherwise it won't compile.
What does it do?
If you understand that a string is nothing more but an array you can iterate over that array and see what kind of value is at the given index. The value at this index is put in a map (remember, a map is a key-value-store). So if you put the Integer 1 in the map where its key is "a", that means "a" occurs 1 time.
By reading the values at the appropriate indexii (very sophisticated plural form of index) with HashMap.get("a") and then incrementing the value by one, we have a nice little letter counter... without the need to predefine numa=0 and so forth. Give it a try and let me know if it werx.
package lettercounter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
/**
*
* #author edm
*/
public class LetterCounter {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String");
String strs = scan.nextLine();
//this map will be populated with the occurrence of the letters in the string.
HashMap<String, Integer> countenLetters = new HashMap<>();
//the next line generates a key-value-store whose key is the letter in the string
//and the value is the accumulated occurrence of said letter.
Arrays.asList(strs.split("")).stream().forEach((String letter) -> {
Integer count = 0;
try {
count = countenLetters.get(letter).intValue();
} catch (Exception e) {
//tried to access a non existing value in the map
//this happens if there is a letter which was not set in the map until now.
//i.e. the first time the letter is encountered.
//this is no error. could have done it with an if also.
}
countenLetters.put(letter, ++count);
});
//do with this stuff what you want;
countenLetters.forEach((k,v) -> {
System.out.println("Letter "+k+" occurs "+v+" times in the string.");
});
}
}

Incorrect logics

So the point of this method is to get an array of temperatures above 100. What is wrong with this? When I return this in my toString it says blazing[] doesnt exist.
public int[] above100Degrees()
{
int[] blazing = new int[temps.length];
for( int i = 0; i < temps.length; i++ )
{
if( temps[i] > 100 )
{
blazing[i] = temps[i];
}
}
return blazing;
}
toString method:
public String toString()
{
String returnString = "The temperature forecast of week " + WEEK + " is logged in as: ";
for( int i = 0; i < temps.length; i++ )
{
returnString += "\t" + temps[i] + "\t";
}
returnString += "\n" + "The number of temperatures below freezing is " + getUnderFreeze() + "." + "\n" +
"The largest difference this week was a net change of " + NetChange() + ".";
for( int i = 0; i < blazing.length; i++ )
{
returnString += "The temperature above 100 degrees is " + above100Degrees() + "." + "\n" + "\t" + blazing[i] + "\t";
}
return returnString;
}
Output
Forecast.java:122: error: cannot find symbol
for( int i = 0; i < blazing.length; i++ )
^
symbol: variable blazing
location: class Forecast
Forecast.java:124: error: cannot find symbol
returnString += "The temperature above 100 degrees is " + above100Degrees() + "." + "\n" + "\t" + blazing[i] + "\t";
^
symbol: variable blazing
location: class Forecast
2 errors
The array is returned by the above100Degrees method. It does not establish the variable name blazing in the scope in which it's called. In fact, you can assign the returned array to a variable named differently.
Try
int[] reallyHot = above100Degrees();
// Then check reallyHot...
for( int i = 0; i < reallyHot.length; i++ )
{
returnString += "The temperature above 100 degrees is " + reallyHot[i] + "." + "\n";
}
Make sure to access the specific element with array access syntax.
Change :
for( int i = 0; i < blazing.length; i++ )
{
returnString += "The temperature above 100 degrees is " + above100Degrees() + "." + "\n" + "\t" + blazing[i] + "\t";
}
to :
int[] blazing = above100Degrees();
for( int i = 0; i < blazing.length; i++ )
{
returnString += "The temperature above 100 degrees is " + blazing[i] + "."; // personalise format
}
Your above100Degrees() function returns the array blazing but you don't invoke that function in your toString() method. As far as toString() is concerned blazing doesn't exist.
Call above100Degrees() from within toString() and save the resulting array to a variable. Then you'll be able to iterate over the (newVariable).length instead of blazing.length.

Categories